1

Please take a look at the following code and fiddle.

CODE

$("#enable").click(function(e) {
    if (!$("#enable").data('isOn')) {
        $("#holder").find('.clickable').each(function(d) {
            $(this).css('border', '1px solid red');
            $(this).addClass('clickEnabled');
        });
        $("#enable").data('isOn', true);
    } else {
        $("#holder").find('.clickable').each(function(d) {
            $(this).css('border', '');
            $(this).removeClass('clickEnabled');
        });
        $("#enable").data('isOn', false);

    }

});

$(".clickEnabled").click(function(e) {
    alert('clicked');
}); 

Fiddle: http://jsfiddle.net/qAuwt/

I am basically trying to toggle a "clickEnabled" class on elements when a button is pressed. The toggling is working as the border is changing however the clickEnabled class is not responding to click events

3 Answers 3

2

There are no .clickEnabled elements when you set the event handler. You can still catch the click event, though:

$(document).on("click", ".clickEnabled", function(){
    alert("Hello, world!");
});​
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't that inefficient due to the fact that all clicks on the document traverse the dom tree every single time?
You don't have to do it this way. See my answer for an alternative.
1

Change:

$(".clickEnabled").click(function (e) {
    alert('clicked');   
});

To:

$(".clickable").click(function (e) {
    if ( $(this).hasClass("clickEnabled") )
    {
        alert('clicked');   
    }
});

As @araxanas mentioned, the .clickEnabled don't exist on load. So I switched the selector to .clickable, which do. However, you only want to handle the click when they're enabled. That's why I've added the conditional. It'll only alert if the clicked element has the clickEnabled class.

Also, it might help to move the css out of javascript, that way you can see visually if the class is there or not, see my updated fiddle.

1 Comment

I like your answer due to the efficiency but it will not work with my code as I bind and unbind events.
-1

The problem is that when page loaded, the click event handler binds to no elements (because there is no element with class 'clickEnabled').

The solution is to change the .click() method to .live() method:

$(".clickEnabled").live('click', function (e) {
    alert('clicked');
});

1 Comment

live is deprecated in jQuery >1.7.

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.