jQuery not working in child window?

1k views Asked by At

When I write:

var x = window.open('','','width=480,height=500');
x.document.write('
<html>
<head>
<link rel="stylesheet" type="text/css" href="chat.css" / >
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"><' +'/script>
<script type="text/javascript">
alert("hi");
<' + '/script>
</head>
<body><p>hi</p></body>
</html>');

I get the alert.

But if I do--

 x.document.write('
<html>
<head>
<link rel="stylesheet" type="text/css" href="chat.css" / >
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
<' +'/script>
<script type="text/javascript">
$(function(){
alert("hi");
});
<' + '/script>
</head>
<body><p>hi</p></body>
</html>');

Then it doesn't work. It does nothing. I've been trying to figure this out all night. Any ideas?

1

There are 1 answers

7
Ja͢ck On BEST ANSWER

This is because jQuery never fires the DOM ready event unless you properly .close() the document after writing into it:

var x = window.open('','','width=480,height=500'),
x.document.write('all your html and script here');
x.document.close();

Due credit: window.open and $(document).ready