jQuery - How to get attribute of an element when using the 'click' event

I'm using jQuery to get a click on an 'a' element. I have a list of those links where each one has a class which by him I'm capturing the click.

I would like to know which of the links has been clicked (I have an attribute 'setid' for each link) and also get the point where the mouse has been clicked.

How could this be accomplished?

example of the code:

<a href="#" class="newItem" setid="28">click me</a>

$('.newItem').click(function (e) {
    alert(e.attr('setid'));
});

EDIT: OK, so to get the position I would use e.pageX

Answers:

Answer

To use jQuery methods you have to wrap this with a call to jQuery.

$('.newItem').click(function () {
    alert($(this).attr('setid'));
});
Answer

refer to the code given below:

document.getElementById("element_id").addEventListener("click",function(e)
{
 console.log(e.srcElement.getAttribute("data-name"));
},false);
Answer

Like Skylar said in the comment to your question, you can use "data-" in front of your new attribute (which is HTML5 valid).

<a href="#" class="newItem" data-setid="28">click me</a>

Then in jQuery (v1.4.3+) you can get it like:

var setid = $(this).data("foo");

It's even a little nicer than attr() that other people have mentioned. See this for more examples - http://www.broken-links.com/2010/11/18/data-attributes-in-html-and-jquery/

Answer

Your code is almost right to get the attribute. The only thing missing is wrapping this (a DOM element) in the jQuery wrapper so you can use jQuery functions. $(this).attr('setid') should work.

To get the page coordinates, use the pageX and pageY properties of the event object. So:

$('.newItem').click(function (e) { // e is the event object
    alert($(this).attr('setid'));
    alert(e.pageX);
    alert(e.pageY);
});

See the documentation on the Event object.

Answer

You're on the correct path.

$(function(){

    $('.newItem').click(function () {
        alert( $(this).attr('setid') );
    })
}); 

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.