Roman
Roman

Reputation: 4513

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

Upvotes: 29

Views: 73024

Answers (5)

user5207771
user5207771

Reputation:

refer to the code given below:

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

Upvotes: 4

Michael K
Michael K

Reputation: 1038

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/

Upvotes: 2

aziz punjani
aziz punjani

Reputation: 25766

You're on the correct path.

$(function(){

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

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237827

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.

Upvotes: 0

BNL
BNL

Reputation: 7133

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

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

Upvotes: 50

Related Questions