0

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 have to do this:

<div id="div1" onClick="divFunction1()">
</div>
<div id="div2" onClick="divFunction2()">
</div>
<div id="div3" onClick="divFunction3()">
</div>
<div id="div4" onClick="divFunction4()">
</div>

But instead do something like this in JavaScript if possible:

div = document.getElementById("allPurposeDiv").onclick...

I'm not exactly sure what would come after onclick is the problem.

Any help is appriciated, Thanks!

2
  • 1
    document.getElementById("div1").onclick = whatever; Commented May 11, 2014 at 5:05
  • I'm not quite sure what you want to do, but maybe having a look at this might help: quirksmode.org/js/introevents.html. Commented May 11, 2014 at 5:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much! This helped a lot and I have been having a hard time with it. :P I am not real good at programming anyway so i appriciate the help!
@Geroy290, glad to have helped
0

You should generally use addEventListener for that

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

    alert('clicked the DIV');

}, false);

or to reference a named function

function divFunction() {
    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 ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.