0

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;
}
Valip
  • 3,998
  • 11
  • 64
  • 127
  • 3
    RTFM... Here we go: http://api.jquery.com/on/ And here for some explaination https://learn.jquery.com/events/event-delegation/ – A. Wolff Jul 20 '16 at 10:23

3 Answers3

2

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();
});
A. Wolff
  • 73,242
  • 9
  • 90
  • 149
pathak tejpal
  • 839
  • 1
  • 8
  • 13
0

Try this:

$('.btn-click').click(function() {
  $(".parent").addClass('newClass');
  $(".display-info").show();
  $('.newClass .display-info').on("click",function() {
     $('.show-this').show();
  })
});
Arun Ghosh
  • 7,312
  • 1
  • 24
  • 38
0

This is because you are using

$('.btn-click').click()

It will work only for static dom, but you are providing a class dynamically that's why it is not working. So for dynamic content always use on() jquery

Mayank Pandeyz
  • 24,624
  • 3
  • 35
  • 55