0

I have a click event in a script associated with a div id - when i move the mouse in the div area and click (the mouse does not change cursor) it does not fire off the event listener how do I make a div area clickable?

<script>
  var myEl = document.getElementById('dealdata');

  myEl.addEventListener('click', function() {
    alert('Hello world');
  }, false);
</script>



<td  BGCOLOR="#91be40" align="center" valign="center">
<div id="dealdata">
<br /><?echo $dpromo;?> 
<h1><?echo $dealvalue; ?></h1>
</div> 
</td>
1
  • yikes - shouldn't have stepped away my code does have dealdata - not sure how that got copied to the stack wrong - question was updated Commented May 16, 2014 at 14:16

3 Answers 3

3

I'm going to guess that dealdata hasn't yet been created when your script runs, because it is underneath the <script> element.

Use an onload handler:

 window.onload = function() {
     var myEl = document.getElementById('dealdata');

     myEl.addEventListener('click', function() {
        alert('Hello world');
     }, false);
 };

As far as your mouse pointer not changing, it's not going to change unless you specifically tell it to. You can do this with CSS:

<style>
    #dealdata { cursor: pointer; }
</style>
Sign up to request clarification or add additional context in comments.

2 Comments

yikes - shouldn't have stepped away my code does have dealdata - not sure how that got copied to the stack wrong
if you remove the items about #ddata - then this is the correct answer thank you! the issue was the <div> was after the script and therefore needed to be placed in the onload Thanks!
3

Change

var myEl = document.getElementById('dealdata'); //your div's id is 'ddata'

to

var myEl = document.getElementById('ddata');

JSFiddle page: http://jsfiddle.net/lisp/Mr2jc/

2 Comments

yikes - shouldn't have stepped away my code does have dealdata - not sure how that got copied to the stack wrong...
OK. Then you can either do what JLRishe suggested to wrap your script inside window.onload = funciont() {...};, or simply put <script> tag somewhere after that <div> tag. The problem in your current code is, when you call var myEl = document.getElementById('dealdata'); the <div> tag has not been created yet. Also see JSFiddle page in my edit.
1

Your divs id is ddata but youre checking for dealdata in your javascript...

1 Comment

yikes - shouldn't have stepped away my code does have dealdata - not sure how that got copied to the stack wrong

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.