Search code examples
javascriptjqueryhtmlhref

Strange behavior of jQuery code in the href attribute


I saw that it's possible place jquery code in the href attribute of the html a tag.

That code, however, works so I do not understand: it works after the second click. Why?

<a href="javascript:alert('ok JavaScript')">JS</a>
<br>
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<a id="myId" href='javascript:
  $(document).ready(function(){
    $("#myId").click(function() {
      alert("ok jQuery");
    });
  });'>jQ</a>


Solution

  • Nothing strange in this behavior.
    There are no jQuery click handlers bound to your link at the beginning.

    However, when you click it at the first time, it executes the following script from its href:

    $(document).ready(function() { 
      $("#myId").click(function() {
        alert("ok jQuery");
      });
    });
    

    and binds a handler to your link. So, after the first click you have no alert, but you now have a click handler bound to your #myId.

    When you click it at the second time, it fires fresh-bound jQuery event, which shows the alert.
    Also, it executes href again, so when you click this link again, you will get two (the same) click handlers and two alerts, and number of alerts will be incremented each time.