How to add onclick to a html element dynamically using javascript

I am able to create a button element and add an onclick event as shown below.

elem.onclick=function()
{
alert("qweqweqwe");
}        

How do I go about using a predefined function instead of defining a function inside of the event? Something like:

elem.onclick=func();

Answers:

Answer

add an eventlistener to the element which has a defined function to call :

elem.addEventListener("click", func, false); //where func is your function name

https://developer.mozilla.org/fr/docs/Web/API/EventTarget/addEventListener

Answer

The best way which i found out for myself is like below.

const li = document.createElement('li');
        li.innerText = "client";
        li.id ="key";
        li.className = "client-class";
        li.setAttribute("onclick","valid;");
Answer

1)

function myfunction(){
alert("hello");
}

elem.onclick=myfunction();

or

2)

var myfunction=function(){
alert("hello");
}
elem.onclick=myfunction;
//or
elem.onclick=myfunction.call();
Answer
var clickHandler = function(){

};

elem.onclick = clickHandler;

function clickHandler(){

};

elem.onclick = clickHandler;

Basically functions are kind of variables in javascript

if done as in method 1, its obvious.

but even if you do it as in method 2, it does the same thing, creates a variable with name clickHandler and type function with value , the function body.

when you do

elem.onclick = function(){};

you are creating an anonymous function without a name, and assigning it to onclick of the element

Meanwhile this method of binding handlers to events are kind of deprecated. Most browsers have better methods to do it, solving many common problems like say adding more than one handlers to same event. Once you understand this concept of functions move on and check the w3c model event registrations as opposed to this traditional model. Using the traditional method is well supported and ok, it just happens that you have better engineered options.

Answer

Using pure javascript

<div id="test">Click me to alert</div>

--

    document.getElementById("test").onclick=callme;

function callme()
{
    alert("You have clicked me!");
}

Demo here

Answer

HTML:

<button>Button</button>
<div id="buttons">
</div>

JS (I used jQuery):

$('button').click(function(){
    var dyn_button = '<button onclick="javascript:test()">Dynamic button</button>'
    $('div#buttons').append(dyn_button + "<br>");
});


function test()
{
    alert(123);
}

http://jsfiddle.net/IceManSpy/FaXgr/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.