Search code examples
javascriptjqueryfunctionready

Calling a jQuery function multiple times


So, I have this function in jQuery:

$(function(){ 
$( ".unfocused" ).click(function ClickHeader () {
    $( this ).addClass( "focused" );
    $( this ).removeClass( "unfocused" );
    $(".header").not(this).addClass( "unfocused" );
    $(".header").not(this).removeClass( "focused" );
});
});

It works perfectly when a header is clicked the first time, but when I try to click another unfocused header, the function doesn't work anymore. Is it because it runs on document .ready?
Thanks for your help!


Solution

  • Change it like this:

      $( document ).on("click", ".unfocused", function() {
        $( this ).addClass( "focused" );
        $( this ).removeClass( "unfocused" );
        $(".header").not(this).addClass( "unfocused" );
        $(".header").not(this).removeClass( "focused" );
      });
    

    This basically registers the event on the document. When you click a header, the event bubbles up to the document. There, the given selector is validated and the function is executed if needed.