Reputation: 1813
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
Upvotes: 1
Views: 112
Reputation: 7204
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.
Upvotes: 1
Reputation: 512
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');
});
Upvotes: -1
Reputation: 11467
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!");
});
Upvotes: 2