Search code examples
javascriptjqueryif-statementaddclasskoken

Koken CMS If class is add class to another element (multiple cases)


Besides a different color for each nav item when they are active i need to have my site-title (logo background color) another color for each page/album.

When a link inside the nav is active, .k-nav-current is automatically appended.

So i've tried this:

if ($("#main li:nth-child(2)").hasClass('.k-nav-current')) {
    $("#site-title").addClass("babycurrent");
} else {

};


.babycurrent{
background: rgb(35,235,0);
}

Or instead of #main li:nth-child() i've tried:
#main a#unique_nav_itemid
a#unique_nav_itemid

But none of these solutions are working.


Solution

  • One method you can use to test to see if the element exists in the document:

    if($('.k-nav-current').length) {
        $("#site-title").addClass("babycurrent");
    }
    

    of course if length is 0, it is considered "falsey". any other positive number is "truthy".

    However, for any further help, we will need to see the actual markup.

    EDIT:

    For your current setup, you are trying to use #main li:nth-child(2) and checking its class. The class is actually applied to the anchor. You need to use #main li:nth-child(2) a

    if ($("#main li:nth-child(2) a").hasClass('k-nav-current')) {
        $("#site-title").addClass("babycurrent");
    }
    

    Though it might be better to just use something like this (considering ids are unique):

    if ($("#baby").hasClass('k-nav-current')) {
        $("#site-title").addClass("babycurrent");
    }
    

    Lastly, if you really want it dynamic, you can do something like this:

    var current = $("a.k-nav-current")[0].id.replace('#','');
    $("#site-title").addClass(current + "current");
    

    EDIT:

    $( document ).ready(function() {
      if ($("#baby").hasClass('k-nav-current')) {
        $("#site-title").addClass("babycurrent");
      }
    });
    
    // or you can do this (commented out) /*
    
    $( document ).ready(function() {
      var current = $("a.k-nav-current")[0].id.replace('#','');
      $("#site-title").addClass(current + "current");
    });
    
    */