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?
-
Check out the jquery docs site!
Specifically, the Click event
-
Could ad an onclick event to alert a attribute
<p id='pWoo' onclick='alert(this.id);'>Woo</p>
Not specific to jquery.
cdmckay : 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). -
The object that was clicked is passed into the click handler as
this
. You can find out the type of element withnodeName
. Like this:function handle_click() { var clicked_element = this; alert(clicked_element.nodeName); } $("#mylink").click(handle_click);
-
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);
-
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/
0 comments:
Post a Comment