user6447029
user6447029

Reputation:

In JQuery, how do I get a reference to the element that was clicked from within my defined click function?

I use this JQuery for handling the situation where someone clicks on a “li” element from my list …

$listItems.click(function(e) {
    e.stopPropagation();
    console.log( $(this) ); 
    var selectedText = $(this).text();
    selectItemFromStyledList($styledSelect, $this, selectedText, $list)
});

I want to put the code into a function, so I’ve tried this

$listItems.click({styledSelect: $styledSelect, selectMenu: $this, listItem: $(this), list: $list}, clickListItem);

However, in my function, the “listItem” parameter is not the list item that was clicked (it looks like the window itself or something). How do I get a reference to the element that was clicked from within my function? It is detailed below …

function clickListItem(event)
{
        var $styledSelect = $(event.data.styledSelect);
        var $selectMenu = $(event.data.selectMenu);
        var $listItem = $(event.data.listItem);     // This is not the item that was clicked
        var $list = $(event.data.list); 

        event.stopPropagation();
        var selectedText = $listItem.text();
        selectItemFromStyledList($styledSelect, $selectMenu, selectedText, $list)
}       // clickListItem

Upvotes: 0

Views: 94

Answers (3)

PeterKA
PeterKA

Reputation: 24638

Just use this or event.target as you normally would, as in the demo below:

function clickListItem(event) {
  console.log( this );
  console.log( event.target );
  console.log( event.data );
}

$(function() {
  $listItems = $('#trinity > li');
  $listItems.click({some:'data',over:'here'}, clickListItem);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="trinity">
  <li>Father</li>
  <li>Son</li>
  <li>Holy Spirit</li>
</ul>

Upvotes: 0

atul
atul

Reputation: 562

$(this) inside the callback function represents the current target element. But when you are passing it to the clickListItem() method you are accessing it outside, which in turn, will represent the current context (e.g window). Therefore pass it in the callback method or use event.target in your method

Upvotes: 0

Cass
Cass

Reputation: 892

Duplicate of get clicked element using jquery on event?.

Use $(this) in the callback function, or use e.target instead of e.data.

Upvotes: 1

Related Questions