Reputation: 3751
I am calling the following function from a button click to open a new window/tab and display an alert and update a text:
function nWin(p) {
var setStyle = "<style rel='stylesheet'>\
.vTop {\
vertical-align: top;\
}\
<\/style>";
var setScript = "<script>alert('test');<\/script>";
setScript += "<script src='http://code.jquery.com/jquery-1.11.0.min.js'><\/script>";
setScript += "<script>$(function () { $('#sText').html('UPDATED TEST'); });<\/script>";
var w = window.open();
var createBody = $(w.document.body);
var createHead = $(w.document.head);
createBody.html("");
createBody.html(p);
createBody.append("<span id='sText'>THIS IS A TEST</span>");
createHead.html(setStyle);
createHead.append(setScript);
}
When I click the button the alert is shown from the page I click the button from rather than on the window/tab that is created and also the sText
text does not change.
Here is a HTML Source:
How can I resolve it so it works correctly, where the alert is shown in the new window/tab and also the span text is updated.
Upvotes: 1
Views: 1067
Reputation: 1
Try this:
function doSomeThing(){
alert('test');
setTimeout('document.getElementById(\'sText\').innerHTML=\"UPDATED TEST\"',500);
document.getElementById('sText').innerHTML="UPDATED TEST";
}
function nWin(p) {
var setStyle = "<style rel='stylesheet'>\
.vTop {\
vertical-align: top;\
}\
<\/style>";
var w = window.open();
var createBody = $(w.document.body);
var createHead = $(w.document.head);
createHead.html(setStyle);
var script = w.document.createElement('script');
script.appendChild(document.createTextNode('('+ doSomeThing+')();'));
(w.document.body || w.document.head || w.document.documentElement).appendChild(script);
createBody.html("");
createBody.html(p);
createBody.append("<span id='sText'>THIS IS A TEST</span>");
}
Upvotes: 0
Reputation:
You need to change your approach to adding content to the new window. The following works;
function nWin(p) {
var setStyle = "<style rel='stylesheet'>\
.vTop {\
vertical-align: top;\
}\
<\/style>";
var setScript = "<script>alert('test');<\/script>";
setScript += "<script src='http://code.jquery.com/jquery-1.11.0.min.js'><\/script>";
setScript += "<script>(function () { $('#sText').html('UPDATED TEST'); })();<\/script>";
var w = window.open();
w.document.write('<head>');
w.document.write(setStyle);
w.document.write('</head><body>');
w.document.write("<span id='sText'>THIS IS A TEST</span>");
w.document.write(setScript);
w.document.write('</body>');
}
See this Fiddle
Upvotes: 1