Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6023513
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T04:01:00+00:00 2026-05-23T04:01:00+00:00

What’s the difference between addEventListener and onclick ? var h = document.getElementById("a"); h.onclick =

  • 0

What’s the difference between addEventListener and onclick?

var h = document.getElementById("a");
h.onclick = dothing1;
h.addEventListener("click", dothing2);

The code above resides together in a separate .js file, and they both work perfectly.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T04:01:01+00:00Added an answer on May 23, 2026 at 4:01 am

    Both are correct, but none of them are "best" per se, and there may be a reason the developer chose to use both approaches.

    Event Listeners (addEventListener and IE’s attachEvent)

    Earlier versions of Internet Explorer implement JavaScript differently from pretty much every other browser. With versions less than 9, you use the attachEvent[doc] method, like this:

    element.attachEvent('onclick', function() { /* do stuff here*/ });
    

    In most other browsers (including IE 9 and above), you use addEventListener[doc], like this:

    element.addEventListener('click', function() { /* do stuff here*/ }, false);
    

    Using this approach (DOM Level 2 events), you can attach a theoretically unlimited number of events to any single element. The only practical limitation is client-side memory and other performance concerns, which are different for each browser.

    The examples above represent using an anonymous function[doc]. You can also add an event listener using a function reference[doc] or a closure[doc]:

    const myFunctionReference = function() { /* do stuff here*/ }
    
    element.attachEvent('onclick', myFunctionReference);
    element.addEventListener('click', myFunctionReference , false);
    

    Another important feature of addEventListener is the final parameter, which controls how the listener reacts to bubbling events[doc]. I’ve been passing false in the examples, which is standard for probably 95% of use cases. There is no equivalent argument for attachEvent, or when using inline events.

    Inline events (HTML onclick="" property and element.onclick)

    In all browsers that support JavaScript, you can put an event listener inline, meaning right in the HTML code. You’ve probably seen this:

    <a id="testing" href="#" onclick="alert('did stuff inline');">Click me</a>
    

    Most experienced developers avoid this method, but it does get the job done; it is simple and direct. You may not use closures or anonymous functions here (though the handler itself is an anonymous function of sorts), and your control of scope is limited.

    The other method you mention:

    element.onclick = function () { /*do stuff here */ };
    

    … is the equivalent of inline JavaScript except that you have more control of the scope (since you’re writing a script rather than HTML) and can use anonymous functions, function references, and/or closures.

    The significant drawback with inline events is that unlike event listeners described above, you may only have one inline event assigned. Inline events are stored as an attribute/property of the element[doc], meaning that it can be overwritten.

    Using the example <a> from the HTML above:

    const element = document.getElementById('testing');
    element.onclick = function () { alert('did stuff #1'); };
    element.onclick = function () { alert('did stuff #2'); };
    

    … when you clicked the element, you’d only see "Did stuff #2" – you overwrote the first assigned of the onclick property with the second value, and you overwrote the original inline HTML onclick property too. Check it out here: http://jsfiddle.net/jpgah/.

    Broadly speaking, do not use inline events. There may be specific use cases for it, but if you are not 100% sure you have that use case, then you do not and should not use inline events.


    Modern JavaScript (Angular and the like)

    Since this answer was originally posted, JavaScript frameworks like Angular have become far more popular. You will see code like this in an Angular template:

    <button (click)="doSomething()">Do Something</button>
    

    This looks like an inline event, but it isn’t. This type of template will be transpiled into more complex code which uses event listeners behind the scenes. Everything I’ve written about events here still applies, but you are removed from the nitty gritty by at least one layer. You should understand the nuts and bolts, but if your modern JavaScript framework best practices involve writing this kind of code in a template, don’t feel like you’re using an inline event – you aren’t.


    Which is Best?

    The question is a matter of browser compatibility and necessity. Do you need to attach more than one event to an element? Will you in the future? Odds are, you will. attachEvent and addEventListener are necessary. If not, an inline event may seem like they’d do the trick, but you’re much better served preparing for a future that, though it may seem unlikely, is predictable at least. There is a chance you’ll have to move to JavaScript-based event listeners, so you may as well just start there. Don’t use inline events.

    jQuery and other JavaScript frameworks encapsulate the different browser implementations of DOM level 2 events in generic models so you can write cross-browser compliant code without having to worry about IE’s history as a rebel. Same code with jQuery, all cross-browser and ready to rock:

    $(element).on('click', function () { /* do stuff */ });
    

    Don’t run out and get a framework just for this one thing, though. You can easily roll your own little utility to take care of the older browsers:

    function addEvent(element, evnt, funct){
      if (element.attachEvent)
       return element.attachEvent('on'+evnt, funct);
      else
       return element.addEventListener(evnt, funct, false);
    }
    
    // example
    addEvent(
        document.getElementById('myElement'),
        'click',
        function () { alert('hi!'); }
    );
    

    Try it: http://jsfiddle.net/bmArj/

    Taking all of that into consideration, unless the script you’re looking at took the browser differences into account some other way (in code not shown in your question), the part using addEventListener would not work in IE versions less than 9.

    Documentation and Related Reading

    • W3 HTML specification, element Event Handler Attributes
    • element.addEventListener on MDN
    • element.attachEvent on MSDN
    • Jquery.on
    • quirksmode blog "Introduction to Events"
    • CDN-hosted javascript libraries at Google
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have an MVC Razor view @{ ViewBag.Title = Index; var c = (char)146;
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.