Create Button with Function after clicking - javascript

I've got some functions...
function myFunction()
{
var btn = "<input type='button' onclick='sf();'>";
var t = document.createTextNode("FINISH GAME");
btn.appendChild(t);
document.body.appendChild(btn);
};
function sf(){window.alert("You finished the game!")};
..and a button that activates the first function.
<button onclick="myFunction()">Click Me!</button>
So when I click on the "Click Me"-button, another button should be created, with the text "FINISH GAME". When clicking on that second button, the text "You finished the game!" should be alerted.
But clicking on the first button, nothing happens. Where's the coding error? Where did I forget a comma? ;)

You are creating input element in wrong way.
function myFunction()
{
var btn = document.createElement('input');
btn.setAttribute('type' , 'button');
btn.setAttribute('value', 'FINISH GAME');
document.body.appendChild(btn);
btn.addEventListener('click','sf',false);
};
function sf(){window.alert("You finished the game!")};
how to create element in JavaScript

It is because your variable btn is not a DOM element but string. You can create input element and set all its attributes like this:
function myFunction() {
var btn = document.createElement('input');
btn.setAttribute('type', 'button'); // input element of type button
btn.setAttribute('value', 'FINISH GAME');
btn.onclick = sf;
document.body.appendChild(btn);
};
or:
function myFunction() {
var btn = document.createElement('button'); // button element
var t = document.createTextNode("FINISH GAME");
btn.appendChild(t);
btn.onclick = sf;
document.body.appendChild(btn);
};

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

I added an onclick attribute to a new button but it only works on the old one

So I am still new to coding and I was just coding quite random stuff when I found out something that is probably me being a bit stupid and not understanding whats fully going on but I thought I'd come over here to ask, why does the generated buttons created not log "test" to the console but the original does and what am I doing wrong?
function newButton() {
var btn = document.createElement("button");
btn.id = "button";
var btnText = document.createTextNode("Click me");
btn.appendChild(btnText);
document.body.appendChild(btn);
document.getElementById("button").onclick = console.log("test");
}
<button id="addButton" onclick="newButton();">Add a button</button>
Thank you very much
function newButton() {
var button = document.createElement("button");
button.innerHTML = "Click Me";
// you have a reference to the button here, so add a handler to it
button.addEventListener('click', () => console.log('test'));
document.querySelector('#newButtons').appendChild(button);
}
<button id="addButton" onclick="newButton();">
Add a button</button>
<div id="newButtons"></div>
At least one issue with your code is that you have many buttons with the same id of "button". I haven't looked more into this than this.
<body>
<button id="button">Click me</button><button id="button">Click me</button><button id="button">Click me</button><button id="button">Click me</button><button id="button">Click me</button><button id="button">Click me</button><button id="button">Click me</button><button id="button">Click me</button></body>
Rename the button id within the function and add onClick function call.
There are two buttons with same id 'button'. Rename either of those ids and add .onClick function. It will work
function newButton() {
var btn = document.createElement("button");
btn.id = "buttonnew";
var btnText = document.createTextNode("Click me");
btn.appendChild(btnText);
document.body.appendChild(btn);
document.getElementById("buttonnew").onclick = function() {
console.log("test"); };
}
Your primary problem is on the onclick assignment in your newButton function.
You're calling console.log("test") which returns undefined, and so "test" is logged to the console and the return value from the log is assigned to on click instead of the logging function, in other words:
document.getElementById("button").onclick = undefined // console.log(...) returns undefined;
You need to wrap your call in another function:
function newButton() {
var btn = document.createElement("button");
btn.id = "button";
var btnText = document.createTextNode("Click me");
btn.appendChild(btnText);
document.body.appendChild(btn);
document.getElementById("button").onclick = function(){
console.log("test")
}
}
<button id="addButton" onclick="newButton();">Add a button</button>
With this change the function:
function(){
console.log("test")
}
will be called whenever you press the button.
Your next problem is that you're using getElementById when if you add buttons multiple times, they'll all have the same Id and only the first will have the event handler, you can fix this by adding the onclick to btn instead of getting the button by it's Id:
function newButton() {
var btn = document.createElement("button");
btn.id = "button";
var btnText = document.createTextNode("Click me");
btn.appendChild(btnText);
btn.onclick = function(){
console.log("test")
}
document.body.appendChild(btn);
}
<button id="addButton" onclick="newButton();">Add a button</button>

Click event in dynamically created Element

I am new to Javascript and learning new things day by day.
Here I need to click the button and new button are created now I need to again click that newly created button and create new button again and so on. It must be in Pure Javascript.Please help me out
document.getElementById("btn").addEventListener("click",function(e) {
var btn=document.createElement("BUTTON");
var t=document.createTextNode("Click Me");
//Some code to click dynamically created element
btn.appendChild(t);
document.body.appendChild(btn);
Create a function to create a button that creates a button. Note: you're not appending the text node to the button.
If you want to watch changes in the DOM and add events to the buttons in a alternative way, check the answers in this question...
var body = document.getElementsByTagName('body')[0];
(function myButton() {
var btn = document.createElement("BUTTON");
var text = document.createTextNode("Click Me");
// append the text to the button
btn.appendChild(text);
// append the btn to the body tag
body.appendChild(btn);
// adds the click event to the btn
btn.addEventListener("click", myButton);
})();
In this case, jQuery do the good jobs for you.
$(function($){
$(document).on('click','button',function(e){
// do your stuff.
})
})
Here is another good answer using jQuery:
Event binding on dynamically created elements?
Simply add a eventlistener to document, then check tag.
You can further expland it by also adding a Id or Class to the buttons and check that aswell (in case you need multiple buttons that does different things)
document.addEventListener('click', function(event) {
var clickedEl = event.target;
if(clickedEl.tagName === 'BUTTON') {
clickedEl.innerHTML = "clicked!";
var btn=document.createElement("BUTTON");
var t=document.createTextNode("Click Me");
btn.appendChild(t);
document.body.appendChild(btn);
}
});
<button>Click Me</button>
Make it a generic function and bind the click events to that method.
function addButton () {
var btn = document.createElement("BUTTON");
btn.type = "button";
var t = document.createTextNode("Click Me");
btn.appendChild(t);
btn.addEventListener("click", addButton);
document.body.appendChild(btn);
}
document.getElementById("btn").addEventListener("click", addButton);
<button type="button" id="btn">Button</button>
Or event delegation
function addButton () {
var btn = document.createElement("BUTTON");
btn.type = "button";
var t = document.createTextNode("Click Me");
btn.appendChild(t);
document.body.appendChild(btn);
}
document.body.addEventListener("click", function(e) {
if (e.target.tagName==="BUTTON") { //I personally would use class or data attribute instead of tagName
addButton();
}
});
<button type="button" id="btn">Button</button>

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>

Passing button value for a dynamically created button

I have elements that are dynamically created. But I can't seem to add a onclick event that passes down the buttons own value. The function itself is not being called.
var btn = document.createElement('button');
btn.innerHTML = "Edit";
btn.value = i;
btn.onclick ="EditData(this.value)"; // <----
function EditData(value) {
alert(value);
}
Set the function itself:
var btn = document.createElement('button');
btn.innerHTML = "Edit";
btn.value = '2';
btn.onclick = EditData;
function EditData(event) {
alert(this.value);
}
You have to assign a function to onclick, not a string:
btn.onclick = function() {
EditData(this.value);
};
Maybe you thought you had to assign a string, because in HTML we would write
onclick="...."
However, the DOM API is different from HTML.
Learn more about events and different ways to bind handlers.

Categories