I am used to using inline events in my websites for example
<head>
<script>
function func() {
alert("test");
}
</script>
</head>
<body>
<div id="mydiv" onclick="func()"></div>
</body>
I noticed that sites these days do not use inline events at all. I know you can set events pragmatically like:
document.getElementById('mydiv').onclick = function(){ func()}
Is this how it should be done? Do I have to put the above line at the end of every page?
How are the keypress,click, and blur events attached to the input fields on this site for example: https://twitter.com/signup
Thanks.
-
@SomethVictory how ironic ... you have asked 5 questions and only accepted an answer on 1 of them ....Manse– Manse2012年07月02日 08:30:19 +00:00Commented Jul 2, 2012 at 8:30
-
That's because I've never got a correct answer! till now, I still could get. Have you seen anyone answer my question correctly and I didn't accept?Someth Victory– Someth Victory2012年07月02日 08:54:13 +00:00Commented Jul 2, 2012 at 8:54
4 Answers 4
Yes, that is one valid way to add an event to an object, but it prevents more than one function from being bound at a time.
I would recommend looking into jQuery (or similar javascript library, like mootools), which is how the vast majority of sites bind their javascript events these days.
For example, in jQuery you generally bind clicks like this:
$("#mydiv").click(function(event) {
// click handling code
});
1 Comment
onclick property.The cleanest way to add event listeners is to use the built in methods :
var el = document.getElementById('mydiv');
if (el.addEventListener) {
el.addEventListener('click', modifyText, false);
} else if (el.attachEvent) {
el.attachEvent('onclick', modifyText);
}
function modifyText() {
}
This promotes cleaner more readable and reusable code. (Note attachEvent is for pre IE9)
You can either place this code at the end of the <body> tag (or anywhere within the <body> tag but after the DOM element is added) or within a window onload function - which executes after the DOM has completed loading :
window.onload = function() {
// here
};
4 Comments
The prefered method is to use addEventListener, often in combination with a library (such as YUI or jQuery) that smooths over variations between browsers (e.g. old-IE not supporting addEventListener).
Do I have to put the above line at the end of every page?
Usually you would put JavaScript in a file of its own, and then src it into each page that needed it.
Comments
The main idea here is that the DOM element that you want to register the handler on should be loaded. so either you do the event binding after the element html, or you could do it in the window.onload event handler, which could be defined before the actual tag definition, like this:
window.onload = function(){
// your event binding
}
But my advice would be to include javascript at the end of the document as much as possible.