mehdi
mehdi

Reputation: 912

how to click on a button after popup windows loaded completely

I want to click on some html element pragmatically. I use Jquery selector to select a button and click it.

$('span.firstBtn').click();

after clicking this button a popup window will show and then I want to click a button in the popup windows.

$('div.BtnOnPopupWindows').click();

but I get null pointer because there is no popup windows when code run. so i need to wait till completion of loading the popup window. how can I do this? how can I wait till completion of loading of the popup window?

Upvotes: 3

Views: 418

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 205987

Use the jQuery's .on() method with delegated event handlers:

// DELEGATED EVENT HANDLERS
// Delegate event for existing or future elements using .on() with delegation:
$(document).on("click", ".BtnOnPopupWindows", function() {
  console.log("BtnOnPopupWindows CLICK");
});

// DIRECT EVENT HANDLERS
// Define button click:
$('.firstBtn').on("click", function() {
  console.log("firstBtn CLICK")
  $('#popup').html(`<div class="BtnOnPopupWindows">TEST</div>`);
});

// Dynamically trigger stuff
$('.firstBtn').click();
$('.BtnOnPopupWindows').click();
<span class="firstBtn">BUTTON</span>
<div id="popup"><!--will be dynamically populated--></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Tip: Instead of using $(document) try always to delegate to a first static (non-dynamic) Element parent. For the above example it would be like:

// Static parent - on click - dynamic child
$("#popup").on("click", ".BtnOnPopupWindows", function() {

Upvotes: 4

Related Questions