Unable to attach click event to a dynamically created button - javascript

I have created a javascript function to dynamically create a button
function btn(d) {
var btn = document.createElement("BUTTON");
var t = document.createTextNode(d);
btn.appendChild(t);
btn.className = "myButton";
btn.onclick = alert('hello');
document.body.appendChild(btn);
}
when this function is called, alert is poping up even if button is not clicked. I want the alert when button is clicked. May be i am missing something. Please help. Thanks

you are calling the alert function not assigning a function
alert('hello'); // evals immediately.
btn.onclick = function () {
alert("Hello World"); // gives the button a click handler
// which can be called when clicked
};

Try doing it with jQuery, like so (per your jQuery tag on the question):
function btn(d) {
var btn = $('<button/>').addClass('myButton').text(d).appendTo('body').click(function (e) {
alert('hello');
})
}

onclick should look like:
btn.onclick = function(){alert('hi');};

You are assigning the return value of alert('hello'); to the onclick, while it is expecting a function. The correct way without jQuery would be
if (btn.addEventListener)
btn.addEventListener ('click',function(){ alert('hello');}, false);
else if (btn.attachEvent)
btn.attachEvent ('onclick',function(){ alert('hello');});

Related

Create just one button using javascript?

I have a HTML button that when you click on it, calls a function. The function is below:
function newButton ()
{
let btn = document.createElement("BUTTON");
btn.innerHTML = "Click me";
document.body.appendChild(btn);
}
I need it so the HTML button can only call this function once (so that it only creates 1 button) otherwise, if you continue clicking the original HTML button, it will just continue creating more new buttons.
Any ideas?
One way would be to keep track of the state in a variable. Something like:
let created = false;
function newButton () {
if (!created) {
// your code
created = true;
}
}
With addEventListener you could listen for an event only once by setting the once option to true. This will remove the event listener after newButton has been called.
const button = document.getElementById('create-button');
function newButton () {
let btn = document.createElement("BUTTON");
btn.innerHTML = "Click me";
document.body.appendChild(btn);
}
button.addEventListener('click', newButton, { once: true });
<button id="create-button">Create Button, but only once.</button>
You can check if button exists, with ID or class exists. If it doesn't create new one. In other case - do nothing.
Sure, just add a if statement and a var (int if you want to create lets say several, boolean if only one), something like that:
var btnAmount = 1;
function newButton ()
{
if(btnAmount == 1) {
//do your thing and create the button
btnAmount--;
}
}
function newButton ()
{
let btn = document.createElement("BUTTON");
btn.innerHTML = "Click me";
document.body.appendChild(btn);
btn.addEventListener('click', newButton, { once: true });
}
document.getElementById('rootButton').addEventListener('click',newButton);
<input type="button" value="Create Buttons" id='rootButton'>
Quick and dirty, without knowing much more about your specific scenario:
function newButton ()
{
let btn = document.createElement("BUTTON");
btn.innerHTML = "Click me";
document.body.appendChild(btn);
newButton = () => {};
}
If you're invoking this function from an event handler, you could set the once option on addEventListener. Doing so will only invoke the method once, while removing the handler for subsequent invocations.
illustration

How to make button do more than one thing after use

First I displayed the div on screen and now I want to use the the button to create that same div(or any other action) after user input.
document.getElementById("add").addEventListener("click", function() {
document.getElementById("welcome").style.display = "block";
}
How do i make the button be able to work again after the first thing it did?
It isn't customary to reuse a UI element in different ways as it tends to confuse the end user. But if you must...
document.getElementById("add").addEventListener("click", showWelcome);
function showWelcome() {
document.getElementById("welcome").style.display = "block";
document.getElementById("add").removeEventListener("click", showWelcome);
reassignButton();
}
function resassignButton(){
// some decision logic for next button function
document.getElementById("add").addEventListener("click", doNextThing);
}
function doNextThing(){
// removes eventlistener on add button. does whatever
}
You can use removeEventListener to remove the handler and then set a new one.
var ele = document.getElementById('btn');
ele.addEventListener("click", function click1(){
//Do stuff for the first click
this.innerHTML = "Click Me Again";
alert("Hello");
//Remove the event hendler
this.removeEventListener("click", click1, true);
//Attach handler for rest of clicks
ele.addEventListener("click", function click2(){
alert("You cicked again!");
}, true);
}, true);
<button id=btn>Click Me</button>
Although it's probably more practical to re-use a single event listener, as assigning and re-assigning event listeners can sometimes lead to memory leaks..
(()=>{
var ele = document.getElementById('btn');
var clicks = 0;
ele.addEventListener("click", function(){
if(clicks){
alert("Thanks for clicking again");
}else{
alert("Hello");
this.innerHTML = "Click again";
}
clicks++;
}, true);
})();
<button id=btn>Click Me</button>
You can make several methods and use these with the onclick attribute of button.
Also I advise you to use jQuery. It's easy and faster than JS.

Can a button delete itself via a function? Javascript

I am creating a reset button, that when clicked should delete itself via a function.
But the deletion works only when fired by any element other than the button itself :( I mean the onclick doesn't work right.
function to create the reset button:
function createButton(context, id , value ,func)
{
var button = document.createElement("input");
button.type = "button";
button.id = id;
button.value = value; // text on button
button.onclick = func;
context.appendChild(button); // add the button to the context
}
the call to the create function:
createButton(document.body , "resetButton" , "Reset Game" , "resetGame();" );
the reset function which suppose to delete the button:
//reminder - id is "resetButton"
function resetGame()
{
var resetBottun = document.getElementById("resetButton");
var parentOfResetButton = resetBottun.parentElement;
parentOfResetButton.removeChild(resetBottun);
};
when I click the button , it should fire the resetGame() function and the button should disappear, but as I mentioned that only happens if I run the resetGame() function from any other place but not the onclick of the reset button.
hope you understand :/
please help
The value of button.onclick needs to be a function.
You are assigning "resetGame();", which is a string.
Pass resetGame instead of "resetGame()".

Onclick event triggering onload for button

I have a div, and I want to append a button created with JS to it, with JS defining the ID, onclick, as well as the text. Everything works fine, except for the onclick event triggers on page load instead of when clicked. When inspected, there isn't even a onclick attribute.
Here is an example:
function createEditButton(num) {
var btn = document.createElement("button");
btn.onclick = myFunc();
btn.type = "button";
btn.innerText = "Edit";
btn.id = "editbutton" + num;
return btn;
}
function myFunc() {
alert("hi");
}
document.getElementById('someDiv').appendChild(createEditButton(5));
<div id="someDiv"> </div>
I have even tried adding the event using addEventListener: btn.addEventListener("click", showEditFields(event), false); and it results in the same. I'm not understanding what I'm doing wrong.
It's b/c you are calling the function instead of referencing it:
btn.onclick = myFunc(); /* <-- remove parens */
btn.onclick = myFunc;
While registering btn.onclick as a click callback you are executing function instead of assigning it. you should use addEventListener method to register click events instead of onclick, the benefits of using addEventListener are it can easily register multiple callback while if suppose you are assigning 'onclick' value twice the first value will get replaced.
And to pass value to function you can use bind function. bind will create new function with given context and arguments bound to it. or you can simply create a wrapper function which will execute the call back function with given arguments.
Bind: MDN Docs
See the below example.
function createEditButton(num) {
var btn = document.createElement("button");
btn.addEventListener('click', myFunc);
// Using Bind to pass value
btn.addEventListener('click', myFuncWithVal.bind(btn, num));
// Uaing Wrapper function to pass value
btn.addEventListener('click', function(event) {
alert('wrapper function');
myFuncWithVal(num);
});
btn.type = "button";
btn.innerText = "Edit";
btn.id = "editbutton" + num;
return btn;
}
function myFunc() {
alert("hi");
}
function myFuncWithVal(val) {
alert(val);
}
document.getElementById('someDiv').appendChild(createEditButton(5));
<div id="someDiv"></div>
function createEditButton(num) {
var btn = document.createElement("button");
btn.onclick = myFunc;
btn.type = "button";
btn.innerText = "Edit";
btn.id = "editbutton" + num;
return btn;
}
function myFunc() {
alert("hi");
}
document.getElementById('someDiv').appendChild(createEditButton(5));
<div id="someDiv"> </div>

Invoke the click handler of a button

I'm trying to invoke the click of a button programatically using JavaScript. My code is:
$(document).ready(function() { autoload(); });
function autoload() {
var button = $("#button");
var video = $("#video");
var evnt = button["onclick"];
// Set the click handler of the button
button.click(function () {
video.get(0).play();
});
// Call the button's click handler
if (typeof button.onclick == "function") {
button.onclick.apply(button);
}
}
But for some reason this is not working, the click handler is not called.
Events in jQuery are different than native DOM events.
You should use button.click() or button.trigger("click").

Categories