Search code examples
jqueryif-statementpathname

in Jquery, How can I use If/else with window.location.pathname.indexOf?


I have a website that is broken into 4 subcategories. each category contains html files that I would like to alter depending on the parent category. Basically, I want jquery to read the folder name of the HTML document and depending on the name, initiate a script. I want each category to target a different class (which I why I need separate categories) I've resolved on this code:

$(document).ready(function() {
  $('.workopen').click(function(e) {
    $(this).siblings('.open').addBack().toggleClass('open');
    e.stopPropagation();
  });

  if (window.location.pathname.indexOf("firstcategory") > -1) {
    $('.work .workopen .four').siblings('.open').addBack().toggleClass('open')
    $('.one .inner2, .two .inner2, .three .inner2').hide();
    $('.etc').css("text-decoration", "underline");
  }
});

it does exactly what I want! but only works on one category at a time (firstcategory). my question is: can I write an if/else statement that will allow me to alter three more categories? or do I have to write 4 seperate JS files?


Solution

  • First pull the path name into a variable. Then you can simply use a series of if-else statements.

    var pathName = window.location.pathname;
    
    if (pathName.indexOf("firstcategory") > -1) {
        // what you want to show/hide
    } else if (pathName.indexOf("secondcategory") > -1) {
        // what you want to show/hide
    } else if (pathName.indexOf("thirdcategory") > -1) {
        // what you want to show/hide
    } else if (pathName.indexOf("fourthcategory") > -1) {
        // what you want to show/hide
    }
    

    I would recommend just adding a single class to each operation you want to apply it to. Elements may have more than one class :)