Hey Im trying to to learn JavaScript at the moment, and I want to be able to create a button on a page that I created in JavaScript, but it always adds the button to index.html instead. Please note I am running this off of WebStorm IDE and don't have a URL/ dont know what to put for window.open(____) because of that.
It successfully creates a new window saying "Hello", but there is no button.
var myWindow=window.open('');
myWindow.document.write('Hello');
var button=myWindow.document.createElement("newbutton");
button.onclick= function(){
alert("blabla");
};
var buttonParent= myWindow.document.getElementById("buttonParent");
buttonParent.appendChild(button)
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");
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);
Related
I am using js to generate a webpage, and need to generate a button. The code is mostly working, but when I try to set the onclick attribute, I run into a problem. The onclick attribute is calling a function, and I need to give it an attribute. I have a variable in my code that contains the value I need to give to the function, but i don’t know how to put this value in the parameters. If this doesn’t make sense, it’s probably because I’m not good at explaining things.
Basically, I have:
var potato = 5;
var btn = document.createElement(“button”);
btn.setAtribute(“onclick”, “coolFunction(potato);”);
When I open the page and go to dev view, the button looks like this:
<button onclick=“coolFunction(potato);”>this is a button</button>
However, I want the value of potato there, instead of potato itself.
Anny Ideas?
You can do this
var potato = 5;
var btn = document.createElement('button');
btn.setAttribute('onclick',`coolFunction(${potato});`);
You could also call an anonymous function with onclick:
btn.onclick = () => coolFunction(potato)
I would forego the inline JS altogether. Add the value of potato to a data attribute on the button, and some text content, and add that to the page.
Next add an event listener to the button. When the click event on the button is fired it calls the function, and that can grab the value of the data attribute and do something with it. Here I'm just logging the value to the console.
const potato = 5;
const btn = document.createElement('button');
btn.textContent = 'Click me for potato';
btn.dataset.potato = potato;
document.body.append(btn);
btn.addEventListener('click', coolFunction);
function coolFunction() {
console.log(this.dataset.potato);
}
var win = window.open('', '_blank', 'PopUp' + ',width=1300,height=800');
win.document.write(`
<div class="col-sm-24">
<p class="page-title headerLabel"></p>
</div>`);
I have a window element with the class headerLabel. In this paragraph tag I want to inject some data which is liable to change... I have tried
var heading = Some Heading;
win.document.write($('.headerLabel').html(heading));
but it's not working
Assuming win is a different window from the one containing this code, you need to tell jQuery to use the other document instead of its default one (the current window). You also don't want write, as you're modifying an existing element.
$(win.document).find(".headerLabel").html("The new content");
should do it, although if you're going to do anything complex with jQuery in another window, it's usually better to load jQuery in the other window and then call that copy.
You could also easily do this without jQuery, which removes that concern:
win.document.querySelector(".headerLabel").innerHTML = "The new content";
The problem is this line: win.document.write($('.headerLabel').html(heading));
// I don't know what is win. So, let's make an example thinking this is another window.
var win = window;
You're trying to write the result of $('.headerLabel').html(heading). So, just call the .html function.
var win = window; // I don't know what is win. So, let's make an example thinking this is another window.
win.document.write(`
<div class="col-sm-24">
<p class="page-title headerLabel"></p>
</div>`);
var heading = "Some Heading";
$('.headerLabel', win.document).html(heading)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am trying to add a close me link to this function. The way this works, is you paste all of this code without newline characters into a bookmark and the bookmark brings up a blue box on the screen.
Here is what I have so far, the close me link I have created is the "eleCloseLink" node I created:
javascript:(
function(){
var pagebody = document.evaluate( '/html/body' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
if (pagebody != null) {
var node = document.createElement("DIV");
node.style.position="fixed";
node.style.color="white";
node.style.background="blue";
node.style.width="350px";
node.style.top="50px";
node.innerHTML = "<br>BLUE BOX<br>2<br>";
var box = pagebody.appendChild(node);
/* Creating close link here */
var eleCloseLink = document.createElement("a");
eleCloseLink.setAttribute('href', 'javascript:( function(){ node.parentNode.removeChild(node); })();');
eleCloseLink.innerHTML = 'close me';
box.appendChild(eleCloseLink);
}
})();
So far I have tried doing this about 10 differen't ways and none have succeeded. The most recent way is putting javascript:( function(){ node.parentNode.removeChild(node); })(); inside of a and that is not working either. I feel like this should be one of the most common things to code as I see them on websites often and therefore there should be a lot of information on it. My scenario may be a little more specific than most b/c the box I am creating is just a DIV element and I am essentially trying to delete the DIV element (i have tried using this as well) with my close me link. Please let me know if anyone has any suggestions on how to create this close me link.
To resolve this, I created a click event listener which called a function that removes the object. To accompany this, I added a id attribute to the DIV object I was trying to remove. When the click event is triggered, the close function then evaluates the div object with XPATH referencing by id attribute. I was then able to run a remove() method on that object.
End Snippet:
/*Create Link in box to close box*/
var eleCloseLink = document.createElement("a");
eleCloseLink.innerHTML = '|CLOSE|';
eleCloseLink.addEventListener("click", CloseBox, false);
eleCloseLink.background = 'red';
box.appendChild(eleCloseLink);
}
/*Function to close the box */
function CloseBox() {
document.evaluate( "//*[#id='thebox']" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue.remove(this);
}
Still not completely sure if I had to use "this" or not in the remove() method as I was calling the remove() method on the object itself. However this is now working.
how to create click button in pure/native JavaScript without using any html tag and css? This button, when the user click it there's a confirmation box will appear then, when the user click the Ok option, there's a popup window will appear.
I have already code in popup window and confirmation box. Here:
if (confirm("Go?") == true) {
popupWindow = window.open('/filename.htm', "name", windowFeatures);
popupWindow.focus();
} else {
test1= "";
}
I want to display the click button under of:
<div class="activityHeaderPanel">
But, I don't have an access or privilege to change or edit the entire html.
Please help me. I'm not really a programmer. Thank you.
var test = document.getElementByClass("activityHeaderPanel");
function whatClicked(evt) {
alert(evt.target.id);
}
test.addEventListener("click", whatClicked, false);
You can use the native DOM API to create document nodes and attach events, using pure Javascript and no HTML.
var myDiv = document.createElement('div');
myDiv.className = 'activityHeaderPanel';
myDiv.onclick = function(){
if(confirm //...
}
To attach the div you created to the existing document you need to find its parent node and use appendChild:
//this will depend on your particular use case. For example, if the parent element is a
// <div id="theParent">
var parentNode = document.getElementById('theParent');
parentNode.appendChild(myDiv);
I have 2 windows home.html and result.html.
In home.html I have a <textarea> #txtinput and a <button> #btn.
In result.html I have another <textarea> #txtresult.
On home.html, if I enter a value into #txtinput and click #btn, I want to open result.html and pass the value of #txtinput into #txtresult.
I've tried the below code from another post, which displays the value in the new window's body but won't display it in my element
var myWindow = window.open();
myWindow.document.body.innerHTML = document.getElementById("txtinput").value;
Is it somehow possible in a simple way? I am relatively new to JavaScript, my courses are ongoing now and I am just curious to know the ways to do it. Any detailed help will be very much appreciated!
I hope i need to elaborate the below code
Button on click function in the home page:
function sample(){
//this will set the text box id to var id;
var id = document.getElementById("text_box_id").id;
//the sessionStorage.setItem(); is the predefined function in javascript
//which will support for every browser that will store the sessions.
sessionStorage.setItem("sent", id);
//this is to open a window in new tab
window.open("result.html","_blank");
}
Retrieve the value in result page:
$(document).ready(function(){
//This sessionStorage.getItem(); is also a predefined function in javascript
//will retrieve session and get the value;
var a = sessionStorage.getItem("sent");
alert(a);
});
For more information about sessionStorage
code.google.com/p/sessionstorage/
developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
I have done same thing as above, am getting values in new window that's great, but that values I am getting only in documet.ready() function. So I am not able to use these values in my JSP. once I got values I need to display them in JSP.
I hope this code help you
This should be in home page:
function sample(id) {
sessionStorage.setItem("sent", id);
window.open("result.html","_blank");
}
This is another way in the same home page function:
function sample() {
var id=document.getElementById("your_required_id").id;
sessionStorage.setItem("sent", id);
window.open("result.html","_blank");
}
This should be in result page:
function sample1() {
var a=sessionStorage.getItem("sent");
alert(a);
}
The id may be your text box id
In result.html, find the Window which opened it, using window.opener and then take your data of interest from that Window.
window.addEventListener('load', function () { // wait for ready
var home = window.opener, txtinput, txtresult;
if (home) {
txtinput = home.document.getElementById("txtinput");
txtresult = document.getElementById('txtresult');
txtresult.value = txtinput.value;
}
}, false);
In home.html, listen for a click on #btn and open result.html
// assuming button exists at invocation time
var btn = document.getElementById('btn');
btn.addEventListener('click', function () {
window.open('result.html');
}, false);
i think that a simple assignment, using the window.opener handle from within the child window, is what you need:
if (window.opener) document.getElementById("#txtresult").value = window.opener.document.getElementById("#txtinput").value;