Search code examples
javascripthtmlonclickhref

Which call faster href vs onclick


Hi~ i want to calling sequence about anchor tag href property and onclick proerty I have some test <a href="https://stackoverflow.com" onclick="alert('asdf');">asdfasdf</a>

and click anchor tag. is result show alert and link stackoverflow but

<a onclick="setTimeout(function(){console.log('asdf')})" href="https://stackoverflow.com" >test</a> this tag first call href proerty! Please explain calling sequence href and onclick and if you know another knowledge explain for me Please ToT


Solution

  • So onclick functions actually run before href. This allows you to do a number of really cool things, like stop the link from executing if you want to like so:

    function stopLink(event) {
      event.preventDefault();
    }
    <a href="www.google.com" target="_blank" onclick="stopLink">click me</a>