Search code examples
javascriptjqueryhrefeach

Add class to all matching hrefs after click event


I am trying to add the class 'active' to all links that have the same href as the one just clicked.

I have multiple modals with duplicated anchor navigation contained within, so MODAL A has a link to MODAL B, and when I click MODAL B the MODAL B link should have the class 'active' within the newly opened anchor.

The code below doesn't add the class active unless I click that same anchor link again, because I presume the URL is still set to #anchor1 when I click #anchor2 so it still tries to add 'active' to #anchor1.

I need a way of clicking #anchor2 then once the url has updated then search for any other links containing #anchor2

OR clicking on #anchor2 then searches for any other link containing #anchor2 and added the class 'active'

jQuery('.featured li a').on( "click", function() {      
    jQuery(".featured li a").each(function() {
    if (this.href == window.location.href) {
        jQuery(this).parent().addClass("active");
    } else {
        jQuery(this).parent().removeClass("active");
    }
    });
});

Solution

  • In scope of click-listener function the window.location.href is not updated to the new value yet. So you need this:

    jQuery('.featured li a').on( "click", function() {
        var currentHref = this.href;     
        jQuery(".featured li a").each(function() {
            if (this.href == currentHref) {
                jQuery(this).parent().addClass("active");
            } else {
                jQuery(this).parent().removeClass("active");
            }
        });
    });