SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Zealot
    Join Date
    Aug 2010
    Posts
    192
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    unable to select anything expect #element

    I want jQuery to respond to a click on any element except <img src="path.jpg" alt="" id="test">

    this code works, but only if I'm clicking on images:
    Code JavaScript:
    $('img:not("#test")').click(function(e){
           alert('ok');
        })

    I really want this but it doesn't work:
    Code JavaScript:
        $('*').not("#test").click(function(e){
             alert('ok');
        })

    What can I do so jQuery will detect a click on any element in the page except #test?

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,189
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    An easier way of going about this is by binding a click event to the document instead of determining if the target element matches anything but #test.

    Code JavaScript:
    $(document).on('click', function(e) {
        if (e.target.id !== 'test') {
            alert('OK!');
        }
    });

  3. #3
    SitePoint Zealot
    Join Date
    Aug 2010
    Posts
    192
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Thanks Chris!

    I like your solution better!

    I found one online that uses 2 queries:

    Code JavaScript:
    $('#test').on('click', function(e) {
        e.stopPropagation();
     
     
    });
     
    $('document').on('click', function(e) {
     
        // respond to any non #test click
     
     
    });

    I thought I understood event propagation, but I'm not sure how stopping it on a non #test click works...

    I think I'll use your way because I have more than 1 situation to handle on different element in anything but it is clicked.
    Thanks!

  4. #4
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,189
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    The example you posted shows how you can make your code more abstract but you would only use that in the case that #test has something special action attached to it, when it comes down to it there are different ways to write the same snippet of code but it all depends on what the click event is doing.


Bookmarks

Posting Permissions

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