0

i have this simple code i just can't get it working.

<html>
<head>
<script type="text/javascript">
window.onload = function () {
  p = document.getElementById("foo");  
 p.click =  function() { alert(p); }; 
 }
</script>
</head>
<body>
<div id="foo" style="position:relative;width:100px;height:100px;background-color:red;"> </div>

</body>

</html>

Javascript is turned on. If i put () after the function i can get it autorun. But still, the onclick is not working after it. Firebug did not show any errors.

Cœur
  • 37,241
  • 25
  • 195
  • 267
The real thing
  • 103
  • 1
  • 2
  • 5

4 Answers4

2

I think you need to add an event-handler/listener for the 'click' event, rather than just specifying 'p.click = ...'

You could try this:

function whenLoaded() {   
  var p = document.getElementById("foo");   
  p.addEventListener("click", function(){alert(p)}, false);   
}   

document.addEventListener("DOMContentLoaded", whenLoaded, false);

*Note: attaching event listeners varies by browser, so youll want to use a library that abstracts the differences... Jquery can do this, and Bean ( https://github.com/fat/bean) is built for this. You could also check out Dustin Diaz's domReady if you're just looking for a small cross-browser DOM-loaded event handler kind of thang -- https://github.com/ded/domready

Thick
  • 451
  • 4
  • 3
  • Cross-browser listeners are only difficult if you use a browser-specific method in the first place. Just assgin the listener to the `onclick` property of the element and it will work in every browser that supports scripting. – RobG Feb 13 '12 at 03:04
1
p.onclick =  function() { alert(p); }; 

and... remember to use var when you create a new var

var p = document.getElementById("foo");  
1

Please update as follow. Try.

 p.onclick =  function() { alert(p); }; 
Thit Lwin Oo
  • 3,388
  • 3
  • 20
  • 23
  • 1
    Yes, it should user var p = document.getElementById("foo"); although it is working. http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript – Thit Lwin Oo Feb 13 '12 at 02:32
0

If you're using jQuery, try this:

$(document).ready(function() {
  p = document.getElementById("foo");  
  $(p).click(function(){ 
    alert(p); 
  });
}); 
Nathan
  • 11,814
  • 11
  • 50
  • 93
Anil D
  • 1,989
  • 6
  • 29
  • 60