0

I want to attach a click event at the document level with

 $(document).click();

And on clicking the element i would like to find out whether it is an anchor tag. If it is an anchor tag, then i will call a method to do something. How can that be done? Any idea?

Amit
  • 25,106
  • 25
  • 75
  • 116
  • Why do you want to do this, instead of `$("a").click(function() { ... });` ? – Peter Ajtai Sep 14 '10 at 19:27
  • @Peter: hey seems like u din check my comment at the end of the page... the problem was there are some 100's of links on a page and user clicks on only one link. hence attaching click event for all the anchors seemed little heavy..! – Amit Sep 15 '10 at 06:39
  • Thanks. Can you observe a difference in performance between the two methods? – Peter Ajtai Sep 15 '10 at 11:42

4 Answers4

0

How about just attaching this function you want to call to all of the anchor tags directly?

$("a").click(function(){ alert("a link!") })

goggin13
  • 7,876
  • 7
  • 29
  • 44
  • I believe this adds a click event on all anchor tags that are there on the document, my user clicks on any one link and attaching click event for all the anchors sounded little heavy – Amit May 11 '10 at 05:11
  • @Amit You're right; just thought it made more sense to me than filtering document-wide clicks. Looks like some other people knew more than me though :) – goggin13 May 11 '10 at 05:36
0

You'll just have to check the event object's target.

$(document).click(function(e) {
  var targ;
  if (!e) var e = window.event;
  if (e.target) targ = e.target;
  else if (e.srcElement) targ = e.srcElement;

  if ($(targ).is('a')) {
    // do your stuff
  }
});

(cross-browser code for getting the event target from quirksmode)

Also, if you're going to attach also other event handlers to the links, make sure you use event.preventDefault instead of just returning false if you want to cancel the link's default action (see this question).

Community
  • 1
  • 1
kkyy
  • 12,214
  • 3
  • 32
  • 27
0
<a href="#anchor">Anchor</a>
<a href="link">Anchor</a>

<script type="text/javascript">
    $(document).click(function(event){
        if(event.target.nodeName === 'A'){
            alert('Anchor');
        } else{
            alert('Not an anchor');
        }
    });
</script>
Ben
  • 16,275
  • 9
  • 45
  • 63
0

@kkyy: What will not work, is, if you are trying to make a request on that click event of that anchor, in Safari (all, windows, iPhone, etc.) e.g. in your code:

if ($(targ).is('a')) {
    var img = new Image(1,1);
    img.onload = function(){};
    img.src = "http://www.google.com/images/logos/somelogo.png?" + new Date().getTime();
  }

If you watch the traffic through any sniffer, you won't see the request above in Safari. Yes, pretty lame!

Peter Ajtai
  • 56,972
  • 13
  • 121
  • 140
Rachit Patel
  • 209
  • 1
  • 5
  • 14