Pavel Valeriu Pavel Valeriu - 4 months ago 10
HTML Question

Click function doesn't work on a new added class

I have a button that adds

newClass
to the parent
div
when clicked and it also shows another button. The next thing that I want to make is to display some text with a click function on
.newClass .display-info
.

All the answers that I've found refer to the jQuery
.live
method, but this is deprecated. Instead I used
.on
method but without any result...

This is the example code:

JSFiddle

HTML:

<div class="parent">
<button class="btn-click">
Click me
</button>

<button class="display-info">
Show text
</button>
<span class="show-this">Text to be displayed</span>
</div>


JS:

$('.btn-click').click(function() {
$(".parent").addClass('newClass');
$(".display-info").show();
});

$('.newClass .display-info').on("click",function() {
$('.show-this').show();
});


CSS:

.display-info, .show-this {
display:none;
}

Answer

always prefer on method relating to document.

inplace of this

$('.newClass .display-info').on("click",function() {
    $('.show-this').show();
});

do like below

$(document).on("click",".newClass .display-info",function() {
    $('.show-this').show();
});
Comments