Maxxx
Maxxx

Reputation: 1179

Jquery .on() method

I want to allow to click on my buttons on conditions. So I use the .on() method to allow to click just when the class "clickable" is present. :

$(".button").on("click", ".clickable", function () { 
  alert("click");
});

$("#stop").click( function () {
  $(".button").removeClass('clickable');
});

But I can't click on my buttons from the beginning. Is my .on() method not correct ?

this my html structure :

<div class="button clickable">1</div>
<div class="button clickable">2</div> 
<div class="button clickable">3</div>

Thank you

Upvotes: 1

Views: 5541

Answers (3)

ShankarSangoli
ShankarSangoli

Reputation: 69905

If you want to allow click only when the button has class clickable then use this code. I am assuming our button has button class in it.

$(".button.clickable").on("click", function () { 
    alert("click");
});

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179046

I am making the following assumption about the HTML structure:

<someelement class="button clickable"></someelement>

It sounds like you may be adding/removing elements to the page, or simply changing the selection of active buttons, you should use the delegate or live form of on using a parent node as the base selector. The simplest to use is document:

$(document).on('click', '.button.clickable', function () {...});

the selector in the second parameter has to be a descendant of the first selector (in this case, $(document)).


If you, instead, called:

$('.button.clickable').on('click', function () {...});

and then removed the clickable class (assume #foo is one of the buttons):

$('#foo').removeClass('clickable')

you'd still fire the event listener when you click on the button, because the event was bound directly on every element in the matched set.

Upvotes: 3

James Montagne
James Montagne

Reputation: 78630

$(".button").on("click", ".clickable", function () { 
    alert("click");
});

The meaning of this is that clicking on any element with the class name of clickable which is WITHIN an element with a class of .button.

I think you want anything with both a class of button and clickable in which case it should be this:

$(".button.clickable").on("click", function () { 
    alert("click");
});

Upvotes: 3

Related Questions