1

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!

1
  • 1
    delegate event in order to get it works for new .unfocused elements (with unfocused class added) and btw no more for old ones (class removed) Commented Nov 17, 2013 at 20:29

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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");
});

3 Comments

As of jQuery 1.7, .delegate() has been superseded by the .on() method. Still valid code, though.
Totally awesome! Works like a charm. :)
@GolezTrol thanks for the comment! I always forget which one is the best to use. About all I can remember is "live" is "dead" (deprecated)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.