1

I want to hide a div using JQuery on click event of another div. The problem is that the div that I want to hide is actually created only when I click on the existing div.

Let me explain with code example:

HTML:

<div class="first">I already exist and I create the second div when I am clicked</div>
<div class="second">I do not exist yet, I am created when first div is clicked</div>

The above is happening by another piece of code that another developer wrote.

I want to write another piece of code that will hide the second div when its created right after first div is clicked.

I do not have the permission to change the original dev's original code.

My JQuery that is not working:

$(".first").on("click",function() {
    $(".second").hide();
});
lwd
  • 37
  • 6

1 Answers1

1

You should use this, cause you have to make this delegate. explanation: https://api.jquery.com/on/

$("body").on("click", ".first",function() {
    $(".second").hide();
});
naxsi
  • 602
  • 3
  • 15
  • Heres the documentation on that https://learn.jquery.com/events/event-delegation/ – Fabian S. Oct 18 '21 at 15:39
  • Aren't the two params `.first` and `click` mixed up? Judging by the documentation (https://learn.jquery.com/events/event-delegation/) the first param should be the event type whilst the second would be the selector. – Fabian S. Oct 18 '21 at 15:41
  • 1
    @FabianSchöner Yaeh, i haven't test this, my mistake. – naxsi Oct 18 '21 at 15:43
  • Would be useful to explain *why* this works. Normally event delegation is used for elements that don't exist at the time the code runs (in this case ".first" as that's being clicked) - so it may be that OP just needed to wrap their code in `doc.ready`. If OP is running their code in doc.ready or after .first exists, then it means their event handler is running before the handler that generates .second. By using event delegation, or, more specifically, event *bubbling*, OPs code will run after any other click event handler. Assuming those event click handlers don't cancel propagation. – freedomn-m Oct 18 '21 at 16:07