5

I have some JQuery written which is intended so when a user navigates to 'page/2/' in Wordpress, an image appears in the sidebar. It's CSS is set to display:none; initially, then I have JQuery change it to display:block; if that URL string is present. The code I wrote has it backwards... so it does this to every page BUT '/page/2/'.

$(document).ready(function() {

var url = window.location.pathname;
if(url.indexOf('/page/2/')){
    $('.sidebarimage').css("display","block");
}});

I always thought if there was no condition set in an If statement, it treats it as true, and anything else as false. Should I put a = 1 or something here? What am I missing?

Many thanks SO

0

2 Answers 2

4

The if block will be entered if the value of the condition is convertible to true. In Javascript any non-zero number is true and the return value of indexOf when the string is not found is -1. Hence any time it's not there it gives back -1 which is seen as true and the if block is entered.

Change the conditional to be explicit to what you're looking for

if (url.indexOf('/page/2/') !== -1) {
  $('.sidebarimage').css("display","block");
}
Sign up to request clarification or add additional context in comments.

5 Comments

So before, when it DID find the /page/2/ string, it returned a 0 (false) instead of a 1? That was only time the true statement didn't actually carry through. Wouldn't it carry through for all tests then?
@RCNeil, It would carry through for every case except where the string began with "/page/2/"
So what # does that if-statement (my original) return when it does contain "/page/2/"? That's what I'm asking. I would think it would be 1, a non-zero #, and in turn, would have the TRUE statement carry through. It was not working when it contained "/page/2/" which makes me wonder what indexOf returns when it finds something....
@RCNeil it would return the index in the string where '/page/2/' begins.
ahhhhhhhhhhh, that clearly shows how little I know about some of the functions I'm using in JQuery. My head is still in PHP. Thanks for clearing that up.
0

This Jquery Code will work only for home page

 $(document).ready(function() {

    var x = location.href;
    var y = location.hostname;
    var z = 'http://' + y + '/';

        if(x == z ){
        $('.class').css("display","block");
    }
        else{
        $('.class').css("display","none");
        }
    });

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.