Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Onclick and reference to the object clicked

Tags:

jquery

click

I've got the following jQuery expression, Inside the function I need a reference to the object that was clicked, is there a way to do this?

$('#tagList li').click(function() {
  /* contents */
});
like image 432
RubbleFord Avatar asked Jun 25 '09 13:06

RubbleFord


People also ask

How do you find the value of clicked elements?

Another way to get the element we clicked on in the event handler is to get it from the event object which is the first parameter in the event handler function. And the following JavaScript code: const onClick = (event) => { console. log(event.srcElement.id); } window.

What is the difference between .click and .on (' click in jQuery?

So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.

How do I know which DIV is clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.

What is Click () method?

The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.


2 Answers

Use

$(this)
like image 141
Matthew Groves Avatar answered Nov 15 '22 20:11

Matthew Groves


you can use the return value

$("#tagList li").bind("click", function(e) {
    alert(e.currentTarget + ' was clicked!');
});

or if you want, you can simple point to the object in jQuery mode

$("#tagList li").bind("click", function(e) {
    alert($(this) + ' was clicked!');
});

if you're new to jQuery, I strongly suggest you to see some screencasts from Remy Sharp in jQuery for Designers, they are great to understand a little bit of how jQuery works, and better yet, how to use the console.log() in order to see the objects that you can use!

like image 38
balexandre Avatar answered Nov 15 '22 20:11

balexandre