Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jun 2006
    Location
    UK
    Posts
    907
    Thanks
    301
    Thanked 2 Times in 2 Posts

    Question jQuery: Clicking anywhere but on a particular A tag

    Hi

    I have a question in jQuery.

    I have a webpage with lots of links, buttons, text etc. The page also has an <A class="mylink" HREF="#">Click here</a> tag.

    What exactly I want is, if I click anywhere on the page, button, text or any other <A></A> tag on that page except the A tag that has the class="mylink", an alert() should popup.

    I tried the following but I still see the alert when I click on the <A class="mylink" HREF="#">Click here</a> tag.


    Code:
    <script>
    
    $(document).ready(function(){
    
       $(document).click(function(){
            alert(123);
      });
    
    
    });
    
    </script>
    Any neat solution for this?


    Thanks in advance.

  • #2
    Gütkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    Just check the event's target:

    PHP Code:
    $(function () {
        $(
    document).click(function (e) {
            if ( ! $(
    e.target).hasClass('mylink')) {
                
    alert(123);
            }
        });
    }); 
    .My new Javascript tutorial site: http://reallifejs.com/
    .Latest article: Calculators — Tiny jQuery calculator, Full-fledged OOP calculator, Big number calculator
    .Latest quick-bit: Including jQuery — Environment-aware minification and CDNs with local fallback

  • #3
    Regular Coder
    Join Date
    Jun 2006
    Location
    UK
    Posts
    907
    Thanks
    301
    Thanked 2 Times in 2 Posts
    Hello

    This seems to be working fine and is also efficient.

    Many thanks for your help.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •