0

when trying to ensure my webpage is using unobtrusive javascript I cant seem to get the onclick event to work in my javascript, it only works as an event in the html tag. here is the code

var dow = document.getElementById("dowDiv");
dow.onclick=function () {}

any reason that this isnt working for me? as all the answers i can find say this is the way to do it, thanks in advance

2
  • Could you post the HTML that has the dowDiv id? Commented Dec 9, 2015 at 15:49
  • Inspect it in console. The error might be there somewhere. Commented Dec 9, 2015 at 17:19

3 Answers 3

2

There could be several reasons based on the information provided.

Most likely, the event function code is being attached before the DOM has finished loading.

Alternatively, you might be using a browser which doesn't support onclick (though this is unlikely!). To guarantee it will work, you can use fallbacks for the main routes of attaching an event:

if (dow.addEventListener) {
  dow.addEventListener('click', thefunction, false);
} else if (dow.attachEvent) {
  dow.attachEvent('onclick', thefunction);
} else {
  dow.onclick = thefunction; 
}
Sign up to request clarification or add additional context in comments.

2 Comments

it was the first answer, thank you! evidentially im a bit of a novice!
It's no problem, I can't think of the number of times I've done the same thing and spent some time scratching my head over why my code wasn't being called!
1

Make sure that you only have one element with the id dowDiv. If you have z-index's on elements and something is over the div it might be blocking the click event on the div.

var dow = document.getElementById("dowDiv");
var out = document.getElementById("out");
var clickCount = 0;
dow.onclick = function() {
  clickCount += 1;
  out.innerHTML = clickCount
}
<div id="dowDiv">Hello onclick <span id="out"></span>!</div>

Comments

0

You can use jQuery to achieve a simple o'clock function.

Make you include jQuery BEFORE you reference your .js file:

<script src="path/to/jQuery.js"></script>
<script src="file.js></script>

With jQuery you can say

$('#dowDIV').click(function(){
   Do stuff here;
})

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.