Reputation: 103
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.
Upvotes: 0
Views: 5458
Reputation: 2009
If you're using jQuery, try this:
$(document).ready(function() {
p = document.getElementById("foo");
$(p).click(function(){
alert(p);
});
});
Upvotes: 0
Reputation:
p.onclick = function() { alert(p); };
and... remember to use var when you create a new var
var p = document.getElementById("foo");
Upvotes: 1
Reputation: 451
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
Upvotes: 2
Reputation: 3438
Please update as follow. Try.
p.onclick = function() { alert(p); };
Upvotes: 1