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!

Answers:

Answer

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.

Answer

Here is a jsfiddle using the delegate operation for handling the event like you need.

http://jsfiddle.net/MN9Zt/2/

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.