I have a rather simple script where I want a div to disappear when jQuery loads, add an “trigger” element on which I can click so that the div appears again. Then the class of the “trigger” is changed and when I click that again, the div should disappear again.. unfortunately the script works fine just until the “trigger” class is changed, if I click it again nothing happens.
QUESTION SOLVED
Here is the working JS:
$(document).ready(function () {
if ($('#Bestellungen #Offene .products')) {
$('#Bestellungen #Offene .products').hide();
$('#Bestellungen #Offene .products').before('<div class="trigger"></div>');
$('#Bestellungen #Offene').on('click', '.trigger', function () {
$(this).addClass('minus').next().show();
});
$('#Bestellungen #Offene').on('click', '.trigger.minus', function () {
$(this).removeClass('minus').next().hide();
});
}
});
And here the HTML:
<div id="Bestellungen">
<div id="Offene">
<table>
<tr>
<td>
<div class="products">blablabla</div>
<td>
</tr>
</table>
</div>
In case of, Dynamically added
classelement you need delegate event. Because, element with dynamicclassoridtreated asdynamicelement with thatclassorid.As you’re adding the class
minusto.triggerlater,so,.trigger.minustreating as dynamic element.So try:
In order to implement a delegate event you need to use
.on()method of jQuery like above.Note
Syntax of
.on()for delegate event is: