Home > front end >  Jquery UI click on link
Jquery UI click on link

Time:02-05

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 >
      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>

CodePudding user response:

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 >
      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

  •  Tags:  
  • Related