1

I'm rather new to Javascript and I can't seem to get a script to run/not run on certain pages.

I have this script on my main page to hide and unhide content:

$(document).ready(function() {
$(".hidden").hide();
$(".show").html("[+]");
$(".show").click(function() {
    if (this.className.indexOf('clicked') != -1 ) {
        $(this).prev().slideUp(0);
        $(this).removeClass('clicked')
        $(this).html("[+]");
        }
        else {
        $(this).addClass('clicked')
        $(this).prev().slideDown(0);
        $(this).html("[–]");
        }
    });
});

I need some coding like this:

if url contains "/post/" then ignore script else run script

It should be a simple fix. I just can't get it to work. Any suggestions?

2 Answers 2

2

The if you're looking for is:

if (window.location.indexOf('/post/') == -1){
    // don't run, the '/post/' string wasn't found
}
else {
    // run
}

indexOf() returns -1 if the string wasn't found, else it returns the index in the string where the first character of the string is found.

The above rewritten with added common sense provided by Jason (in comments, below):

if (window.location.indexOf('/post/') > -1){
    // run, the '/post/' string was found
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would write this as if (window.location.indexOf('/post/') >= 0){ // code to run here } to avoid the (confusing) empty if block.
1

According to this answer,

window.location is an object, not a string, and so it doesn't have an indexOf function.

... So window.location.indexOf() will never work.

However, as guided by the same answer, you could convert the URL to a string with window.location.href to then perform searches. Or you could access parts of the URL, like this:

if (window.location.pathname === '/about/faculty/'){ ... } for an exact match

or

window.location.pathname.split( '/' ) to get parts of the url, as mentioned in this answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.