Jump to content

Assigning Event Handlers?


davej
 Share

Recommended Posts

So what are all the different ways of assigning event handlers and are they all equally capable and equally flexible? You can put them in the HTML:

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">1</div>

You can assign them with a statement:

document.getElementById('div1').ondrop = drop;document.getElementById('div1').ondragover = allowDrop;

You can add them as listeners:

document.getElementById('div1').addEventListener('drop', drop, false);document.getElementById('div1').addEventListener('dragover', allowDrop, false);

Any other methods?

Link to comment
Share on other sites

I'll call these Strategies 1, 2, and 3. Strategy 1 is seriously deprecated. As a rule, keep javascript out of your tags. Good style separates structure from behavior whenever possible. Strategy 2 is still available and intuitive. I still prefer it. Note that in place of a function name you can use an anonymous function. (Ignore that point if it means nothing to you.) The big drawback to this strategy is that you can assign only one function at a time. The workaround is to create a "container" function that executes multple functions. Another drawback is that, if you link to a poorly constructed 3rd-party script, it might also assign a function to an event listener, and then yours or it would be overwritten. There is a common workaround for that too. Strategy 3 is the W3 standard and eventually all scripts will do that. Unfortunately, it doesn't work in IE versions before 9. There's a workaround here. Strategy 4 is to use jQuery and let it do the work for you. I don't do that because I'm a purist, and I appreciate that you're trying to learn what's under the hood.

  • Like 1
Link to comment
Share on other sites

Yes, I very much prefer to keep my Javascript out of my HTML, but I don't feel confident about the equivalences. In the HTML they can specify the passed parameter, and sometimes they pass the event and sometimes they pass 'this'. I don't know how that is accomplished with the other methods. Thanks.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...