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
  • 4,440
  • 19
  • 79
  • 150
  • 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
  • 74,033
  • 9
  • 94
  • 155
pathak tejpal
  • 838
  • 1
  • 7
  • 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,634
  • 1
  • 26
  • 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
  • 25,704
  • 4
  • 40
  • 59