views:

109

answers:

5

Hi,

In jquery, how can I figure out what object was clicked?

Is there a way to alert(...) the type of tag? like if it was an <a href> or a <img> etc?

A: 

Check out the jquery docs site!

Specifically, the Click event

Gregory
A: 

Could ad an onclick event to alert a attribute

<p id='pWoo' onclick='alert(this.id);'>Woo</p>

Not specific to jquery.

Pat
In practice, you should probably not embed JavaScript in your HTML... you're better off using an Unobtrusive JavaScript approach (http://en.wikipedia.org/wiki/Unobtrusive_JavaScript).
cdmckay
+3  A: 

The object that was clicked is passed into the click handler as this. You can find out the type of element with nodeName. Like this:

function handle_click() {
   var clicked_element = this;
   alert(clicked_element.nodeName);
}
$("#mylink").click(handle_click);
Magnar
+2  A: 

Magnar's answer is correct as long as you want to know what type of element handled the event (what you attached the event to). If you want to know exactly what element was clicked, including the element's children, you need the event.target property. Using Magnar's example:

// show the type of the element that event handler was bound to
function handle_click() {
    var clicked_element = this;
    alert(clicked_element.nodeName);
}

// show the type of the exact element that was clicked, which may be a child
// of the bound element
function handle_child_click(e) {
    var clicked_element = e.target;
    alert(clicked_element.nodeName);
}

// show the type of the element that matches "#myLink"
$("#mylink").click(handle_click);

// show the type of the element that matches "#myLink" or any of its children
$("#mylink").click(handle_child_click);
Matthew Crumley
A: 

Might not be what you want but I found this tutorial interesting: http://css-tricks.com/tracking-clicks-building-a-clickmap-with-php-and-jquery/

Ross