Dan Hastings
Dan Hastings

Reputation: 3280

Jquery Bind click event to elements in child window

I have code that will create a child window and inside this window I want to be able to fire an alert whenever a user clicks on one of the defined html elements. The code will work as I want it to on the main window, but when I apply it to the child window it doesn't work.

When the method below runs it will output "Window loaded" to the console window, but it doesn't ever launch the click event.

function OpenUrl()
{
    var url = $("#urltoopen").val();
    var childwindow = window.open(url, '', 'width=800, height=500');
    childwindow.focus();
    $(document, childwindow.document).ready(function(){
        console.log("Window loaded");
        $( "div, span, li, ul, ol, input, button", childwindow).click(function(e) {
            console.log("Child click event");
            e.preventDefault();
            e.stopPropagation();
            alert("element clicked");
        });
    }); 
}   

Upvotes: 1

Views: 1117

Answers (2)

Azad
Azad

Reputation: 5264

use jquery contents function to find child window elements

this is a working sample try it on localserver

main.html

   <html>
      <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      </head>
  <body>

      <button onclick=OpenUrl()>OPEN</button>

<script>

    function OpenUrl(){

var childwindow = window.open('test.html', '', 'width=800, height=500');
$(childwindow.document).ready(function(){

    setTimeout(function(){

        $(childwindow.document).contents().find( "button").click(function(e) {
            console.log("Child click event");
        });
    },500);
}); 
}



 </script>

test.html

<html>

<body>

<button>test</button>
</body>

</html>

Upvotes: 1

Mohsen Govahi
Mohsen Govahi

Reputation: 34

Check if $( "div, span, li, ul, ol, input, button", childwindow) contains any selection?

If there are any selections, check selected elements have correct size on new window.

Upvotes: 0

Related Questions