Creating A New Window That Has A Button In Javascript
Solution 1:
It looks as though you're creating a new window called myWindow, and writing the text hello to it. However, the container with the id "buttonParent" does not reside within the new window, but rather the document that index.html is in.
Try this out:
var newDiv = document.createElement("div");
newDiv.id = "newButtonParent"//make sure you pick a unique id
myWindow.document.appendChild(newDiv);
var buttonParent= myWindow.document.getElementById("newButtonParent");
buttonParent.appendChild(button);
Edit: Fixed a typo. From:
var buttonParent= myWindow.document.getElementById("buttonParent");
to
var buttonParent= myWindow.document.getElementById("newButtonParent");
Solution 2:
When was the element with the ID buttonParent created? If this is your entire snippet, you'd first need to create that element as well, otherwise .getElementById
isn't going to find anything in the new window, meaning .appendChild
won't work properly.
The other thing to note is that alert
is a property of the window
object, so just calling alert('!')
will attach the alert the the main window. You need to call it as myWindow.alert('!')
to have it fire on the new window.
Also, document.createElement
takes a tag name, so if you want default button behaviour it should be
myWindow.document.createElement('button');
Here's a working example. I've set the background of the container element to red so you can see it is there.
DEMO - (Click the run button.)
var w = window.open(''),
button = w.document.createElement('button');
button.innerHTML = 'My Button';
button.addEventListener('click', function () {
w.alert('!');
});
var container = w.document.createElement('div');
container.id = 'buttonParent';
container.style.background = 'red';
w.document.body.appendChild(container);
container.appendChild(button);
Post a Comment for "Creating A New Window That Has A Button In Javascript"