Search code examples
javascriptjqueryonclickclick

Jquery UI click on link


I have some links within div. If users click any area in the div, it should do something. But it should do something else if users click on a link.

How could I find out if the click is on a link? BTW, I cannot use onclick() function on the link.

<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
  </head>
  <body>
    <div class="mydiv">
      do something<br />
      <a href="#"> do other</a><br />
      do something<br />
    </div>

    <script>
      $(document).ready(function () {
        $('.mydiv').click(function () {
          var ahref = $(this).attr('href');
          if (ahref == null) {
            alert('do something');
          } else {
            alert('do other');
          }
        });
      });
    </script>
  </body>
</html>

Solution

  • You can use the nodeName property to check whether the clicked element is having an a tag or not.

    <html>
      <head>
        <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
      </head>
      <body>
        <div class="mydiv">
          do something<br />
          <a href="#"> do other</a><br />
          do something<br />
        </div>
    
        <script>
          $(document).ready(function () {
            $('.mydiv').click(function (e) {
              if (e.target.nodeName == 'A') {
                alert('do other');
              } else {
                alert('do something');
              }
            });
          });
        </script>
      </body>
    </html>

    https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName