Skip to content Skip to sidebar Skip to footer

How To Use Onclick In Javascript

I need to know how to use onclick so that it allows me to reuse the onclick method of a div over and over again and not have to add an infinite amount of them. I don't want to ha

Solution 1:

onclick is case sensitive. So it is onclick. It expects a callback function to be assigned to it, which will be called.

document.getElementById("div1").onclick = divFunction;

If you are trying to add more events, then you need a event listener like what adeneo has suggested.

Solution 2:

You should generally use addEventListener for that

document.getElementById('div1').addEventListener('click', function() {

    alert('clicked the DIV');

}, false);

or to reference a named function

functiondivFunction() {
    alert('clicked the DIV');
}

document.getElementById('div1').addEventListener('click', divFunction, false);

I have no idea why this would help you not add an infinite amount of elements ?

Post a Comment for "How To Use Onclick In Javascript"