Move jQuery event handlers from main window to popup

Viewed 171

I am having problems with event jQuery events on a popup window.

In my main window I have a div acting as a window/dialog that has varying content. I have a button to 'pop out' the 'window' into a popout, allowing users with multiple screens to use my app across them.

How it works, is when the button is pressed, a popup opens with the destination of 'popout.html', onload 'popout.html' calls a function to grab the contents of the div from the main page and place it into the popout. so the content dissapears from the main window and appears in the popup.

That is all working fine, Except any event handler I attach with jQuery like $('<button>Do Something</button>').on('click', console.log).appendTo(newBoxContent); still gets executed on the main window, not the popup. How do I move all these events?

2 Answers

I do not think that is very simple or even possible to "transfer".

You can include the script that set up the event handlers in the parent document in the new window. This is needed because a new window will not inherit handlers

Alternatively pass in the scope in the function that sets the event handlers

function setHandlers(scope) {
  $('element.class',scope).on('click', console.log);
}

$(function() {
  sethandlers(window)
  $("#pop").on("click",function() {
   const w = window.open("popup.html");
   if (w) setHandlers(w)
 })
})

I have created a small sample to copy the entire content of a page including scripts. You can strip the script code, then may be append it in the new page load and then reattach events.

$('a').on('click', function () {
    $('body').append($('<div />').text($('form').html()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a href="#">Click Me</a>
<form>
<input type="text" />
<input type="text" />
<input type="text" />

<script>
$("input").on("click",function(){alert("x");});
</script>
</form>

Related