HTML DOM createElement() [duplicate] - javascript

I'm trying to use javascript to create a button that has a onclick event that calls a function defined in the head that takes in as parameter a dom object relative to the button. how do i do this?
ex:
<html>
<head> <script>function blah(obj){alert(obj.value)}</script></head>
<body>
<button onclick="blah(this.parentNode.value);"></button>
</body>
</html>
javascript:
var newButton = document.createElement("button");
???
in the end i want the new button to be the same as the existing one.

function createButton(context, func) {
var button = document.createElement("input");
button.type = "button";
button.value = "im a button";
button.onclick = func;
context.appendChild(button);
}
window.onload = function() {
createButton(document.body, function() {
highlight(this.parentNode.childNodes[1]);
// Example of different context, copied function etc
// createButton(this.parentNode, this.onclick);
});
};
Is that what you want?

You can also use the built-in setAttrbute javascript function.
var newButton = document.createElement("button")
newButton.setAttribute("onclick", "blah(this.parentNode.value)")
Hope it will help

Related

How do I add a button to a div class on load from Javascript? [duplicate]

This question already has answers here:
How to add onload event to a div element
(26 answers)
Closed 5 years ago.
For an assignment, I cannot touch the HTML code and am editing an external JS file. I have to refer the code to an existing class and turn that into a button to run a script.
The has to be ran on load to transform an element with a given id into a button that can also run a function on click.
So let's say the we have id="bar",
how do I go about it?
My code doesn't work at all.
document.getElementById("bar").onload = function () { myFunction() };
function myFunction() {
document.getElementById("bar").innerHTML = "<button></button>";
}
Why don't you just execute your script as the DOM is ready? To do so,
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("bar").innerHTML = "<button></button>";
}, false);
You just need a createElement function.
This works:
document.addEventListener("DOMContentLoaded", function(){
var button = document.createElement("button");
button.innerHTML = "This is a button";
// assuming the Div's ID is bar
var div = document.getElementById('bar');
div.appendChild(button);
//the following function will alert a window when the button is clicked
button.addEventListener ("click", function() {
alert("Button was clicked");
});
});
Updated Codepen
I think this is bit tha you needed
var bar = document.getElementById('bar');
window.onload = function() {
var barInner = bar.innerHTML;
bar.innerHTML = '<button>' + barInner + '</button>';
}
bar.onclick = function() {
alert("Hello\nHow are you?");
};
document.getElementById("bar").onload = myFunction();
function myFunction() {
document.getElementById("bar").innerHTML = "<button>Button</button>";
}
There you go!
Not every single HTML element has a load event.
Only some of them are concerned, such as the window, an image... etc
Have a look here on MDN to learn more about this.
Here is a simple snippet resolving all what you mentioned.
window.addEventListener("load", () => {
// you can put your entire script in here.
var elt = document.getElementById("bar"),
button = document.createElement("button");
button.textContent = elt.textContent;
button.onclick = callback;
elt.textContent = '';
elt.appendChild(button);
function callback() {
console.log("The button has been clicked");
}
});
<div id="bar" style="background: beige; height: 2em">Click me</div>
In the previous snippet, I am appending the button in the element. But if the matter is really to transform it into a button, there we go:
window.addEventListener("load", () => {
// you can put your entire script in here.
var elt = document.getElementById("bar"),
container = elt.parentNode,
button = document.createElement("button");
button.id = elt.id; // if you want to keep the id
button.textContent = elt.textContent;
button.onclick = callback;
container.removeChild(elt);
container.appendChild(button);
function callback() {
console.log("The button has been clicked");
}
});
<div style="background: #fee; height: 2em">
<div id="bar" style="background: beige; height: 2em">Click me</div>
</div>

Using addEventListener() in a for loop with various listeners

I'm trying to add listeners to a number of buttons using a for loop. The appropriate listener for each button is indicated by the ID attribute of the button. Button IDs follow the form "button-[listenerName]". I get the list of all my button elements using querySelectorAll(), and then I iterate through that list, slicing out the name of each listener from the name of each button element. Then, I use the name of the listener with addEventListener() in an attempt to associate that button with its listener.
<!DOCTYPE html>
<html>
<body>
<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>
<p id="demo"></p>
<script>
var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
button.addEventListener("click", listenerName);
}
var listener1 = function() {
document.getElementById('demo').innerHtml = "1";
}
var listener2 = function() {
document.getElementById('demo').innerHtml = "2";
}
var listener3 = function() {
document.getElementById('demo').innerHtml = "3";
}
var listener4 = function() {
document.getElementById('demo').innerHtml = "4";
}
</script>
</body>
</html>
Unfortunately, it doesn't work. What's up with that? Thank you.
There are 3 issues with your code:
In your for loop, you are essentially attaching strings as eventlisteners. You need to access your event listeners from the string you have.
Since you eventlisteners are declared in the global scopre, you can use window to access them:
button.addEventListener("click", window[listenerName]);
You are attaching the event listeners before declaring them. You need to declare listener1 and so on before your for loop
innerHtml does not exist. The right syntax is innerHTML
Here is a working example:
<!DOCTYPE html>
<html>
<body>
<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>
<p id="demo"></p>
<script>
var listener1 = function() {
document.getElementById('demo').innerHTML = "1";
}
var listener2 = function() {
document.getElementById('demo').innerHTML = "2";
}
var listener3 = function() {
document.getElementById('demo').innerHTML = "3";
}
var listener4 = function() {
document.getElementById('demo').innerHTML = "4";
}
var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
button.addEventListener("click", window[listenerName]);
}
</script>
</body>
</html>
your line button.addEventListener("click", listenerName); tried to add a function called listenerName to the click event, and since listenerName is a variable and not a function, it doesn't work.
You could use an array of function to make it work instead.
var array_of_functions = [
'listener1' : listener1,
'listener2' : listener2,
'listener3' : listener3,
'listener4' : listener4
]
and then in your loop you could create the listener by giving the right function:
button.addEventListener("click", array_of_functions[listenerName]);
Also, make sure you create the function and the array before running the loop or they won't exist yet when the code runs.
There's a slightly easier way to do this - just have one function that handles the event:
for (var button of allButtons) {
button.addEventListener("click", handleClick, false);
}
function handleClick() {
var id = this.id.match(/button-listener(\d)/)[1];
document.getElementById('demo').innerHTML = id;
}
DEMO
Or, you can change your loop like this and your code will work
allButtons.forEach(function (button, i) {
var listenerName = button.id.slice(button.id.lastIndexOf("-") + 1);
button.addEventListener("click", function () {
document.getElementById('demo').innerHTML = i + 1;
});
});

Including strings as parameters for a function chosen for .setAttribute to a button in javascript

I want to be able to pass along a string as a value for a button's onclick function using setAttribute. I am getting the error that "add is not defined" when I click on the button and I am not sure what I am doing wrong.
var AddButton = document.createElement("button");
var AddString = "add";
var SectorString = "1_1";
AddButton.setAttribute("onclick",'AddOrDeleteDiv(AddString,SectorString)');
function AddOrDeleteDiv(AddString, SectorString) {
//code
}
Do not use content attribute event handlers! Use event listeners instead:
var addButton = document.createElement("button");
var addString = "add";
var sectorString = "1_1";
addButton.addEventListener('click', function() {
addOrDeleteDiv(addString, sectorString);
});
function addOrDeleteDiv(addString, sectorString) {
//code
}
Well js is known for not having nice methods for string joining and please try to use function parameter names not same as global variable names, it's not a nice thing to do.
var AddButton = document.createElement("button");
var AddString = "add";
var SectorString = "1_1";
AddButton.setAttribute("onclick",'AddOrDeleteDiv(' + JSON.stringify(AddString) + ',' + JSON.stringify(SectorString) + ')');
function AddOrDeleteDiv(addStr, secStr) {
//code
}
or as #Thomas said you could use acutual javascript event handler like , not modifying attributes to assign event handler
AddButton.onclick = function(){AddOrDeleteDiv(AddString,SectorString);}

Creating two elements using js and then having access to them later in another function

I am building some js functionality where I will be creating 2 elements on a page
var createBtn = function(
var btn = document.createElement('button')
...
)
var createIframe = function(
var iframe = document.createElement('iframe')
...
)
Pretty basic stuff, but later on I want to add an event listener to the button that will apply a style attribute to the iframe.
Something like:
var displayIframe = function(
Iframe.style['display'] = 'block'
)
button.addEventListener('click', displayIframe)
My question is how can I access the elements after I have created them without going through the annoyance of attaching classes to them and accessing them all over again that way. Is there someway of getting access to them in the create functions from the beginning.
Your codes is almost correct, but some changes is needed
var btn, iframe;
var createBtn = function () {
btn = document.createElement('button');
...
}
var createIframe = function () {
iframe = document.createElement('iframe');
...
}
Callback function
var displayIframe = function(){
iframe.style['display'] = 'block'
}
Attach click listener
btn.addEventListener('click', displayIframe);
Your mistakes:
you should declare btn and iframe as global variables to be accessible to other functions
function starts with { and ends with } not (, )
so far your codes is correct, without any error, but you won't see anything on the page because you have not attached your newly created elements to the body, For accomplish this try this function
function attachToBody(){
document.body.appendChild(btn);
document.body.appendChild(iframe);
}
In your example, I dont know why you use functions to create element, but you must have your point. Try this and let me know does this work for you.
//this is equivalent to: var btn = document.createElement('button');
var btn = (function(){
var btn = document.createElement('button');
return btn;
})();
var iframe = (function{
var iframe = document.createElement('iframe');
return iframe;
})();
document.getElementById("parentId").appendChild(btn);
document.getElementById("parentId").appendChild(iframe);
btn.addEventListener('click', function(){
iframe.style.display = "none";
});
var createBtn = function() {
var btn = document.createElement('button')
btn.setAttribute("id", "myButton");
return btn;
}
var createIframe = function() {
var iframe = document.createElement('iframe')
iframe.setAttribute("id", "myFrame");
return iframe;
}
document.body.appendChild(createBtn()); // Append button to body.
document.body.appendChild(createIframe()); // Append iFrame to body.
// Get Elements by Id.
var myButton = document.getElementById("myButton");
var myFrame = document.getElementById("myFrame");
// Add event listener.
myButton.addEventListener("click", function() {
myFrame.style.display = "none", false);
}

javascript function is not defined on button click

i am dynamically creating a button element and on its onclick event seting a function call but its always saying removeimg is not defined (removeimg is name of function being called on click of button). hers the code :
link :
http://shri-ram.lifekloud.com/pilot/step4.php
(tab add delete photos)
function removeimg(){
//make request to remove the name
document.getElementById(name).style.display = 'none';
document.getElementById(btn12).style.display = 'none';
}
function showUploadedItem (source) {
var list = document.getElementById("image-listalbum"),
li = document.createElement("li"),
img = document.createElement("img");
var btn = document.createElement('input');
btn.setAttribute("type", "button");
btn.setAttribute("value", "Remove");
btn.setAttribute("class", "t-button");
var btnId = "btn" + source + "";
btn.setAttribute("id", btnId);
var func = "removeimg()";
btn.setAttribute("onclick", func);
img.src = 'uploads/'+source;
li.appendChild(img);
li.appendChild(btn);
list.appendChild(li);
}
Try
btn.onclick = removeimg;
rather than the string version you're doing.
Functions in Javascript have a scope, because they are essentially the same as any other Object. Since your function is defined inside the $(document).ready(); function it only exists in that scope. You'll have to declare it outside the ready() function to use it on the click of a button.

Categories