Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding CSS class based on URL string through JQuery

Tags:

jquery

url

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

like image 655
RCNeil Avatar asked Oct 09 '22 22:10

RCNeil


1 Answers

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");
}
like image 173
JaredPar Avatar answered Oct 12 '22 09:10

JaredPar