tags:

views:

44

answers:

4

Hi,

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?

A: 

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

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

goggin13
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
@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
A: 

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

kkyy
works fine...! Thanks.. :)
Amit
A: 
<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
Thanks Ben.. :)
Amit
You're welcome.
Ben
A: 

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

Rac123
@Rac - Please indent code 4 spaces to format as such.
Peter Ajtai