-2

I created a button where when clicked on creates another button but Iam not sure how to make an onclick event for that button

function boyFunction(){
    var btn1 = document.createElement("BUTTON");
    var x = document.createTextNode("basketball");
    btn1.appendChild(x);
    document.body.appendChild(btn1);
    btn1.classList.add('btn1');
}

I want to be able to click the basketball button and have that button show an image

user1579234
  • 501
  • 5
  • 15

4 Answers4

0

You can add an Click Handler like this:

document.getElementById('button').onclick = function() {
   alert("button was clicked");
}​;​

of course you need to give your new button the id 'button' or any other id you choose

MaZoli
  • 1,388
  • 1
  • 11
  • 17
0

Three things had to be done.

First your new element will need an id

btn1.setAttribute("id", "myButton");

click event handler will need to be created for your new element

document.getElementById("myButton").addEventListener("click", myButtonClickHandler);

and then you will define your click handler in a new function

function myButtonClickHandler {
// my code
} 

Your code after doing the above change will look like below:

function boyFunction(){
    var btn1 = document.createElement("BUTTON");
    btn1.setAttribute("id", "myButton");
    var x = document.createTextNode("basketball");
    btn1.appendChild(x);
    document.body.appendChild(btn1);
    btn1.classList.add('btn1');

    document.getElementById("myButton").addEventListener("click", myButtonClickHandler); 
}

function myButtonClickHandler {
// my code
}
user1579234
  • 501
  • 5
  • 15
0

Can work like this:

function boyFunction(){
    var btn1 = document.createElement("BUTTON");

    // your "onclick function" goes here
    btn1.onclick = function () { };

    var x = document.createTextNode("basketball");
    btn1.appendChild(x);
    document.body.appendChild(btn1);
    btn1.classList.add('btn1');
}
Vadi
  • 3,279
  • 2
  • 13
  • 30
0

You can simply do this

 function boyFunction(){
        var btn1 = document.createElement("BUTTON");
        btn1.addEventListener('click',()=>console.log('clicked'));
        var x = document.createTextNode("basketball");
        btn1.appendChild(x);
        document.body.appendChild(btn1);
        btn1.classList.add('btn1');
    }
Cuong Vu
  • 3,423
  • 14
  • 16