jmack jmack - 2 months ago 8
jQuery Question

Saving the clicked element and accessing it from another object

What i would like to do is set a click event on a particular set of DOM elements.

I would like to remember which element has been clicked as I may need to retrieve some information from it later.

I would then like to be able to access it from another JS object if possible.

Below is what I have so far...

<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<button>
Which have you clicked on?
</button>

<script>
var listItem = {
elementHandle: $('li'),
instanceClicked: '',
bindEventHandlers: function(){
$(this.elementHandle).click(this.alertTheContent);
},
alertTheContent: function(){
this.instanceClicked = $(this);
alert(this.instanceClicked.html());
}
}

var button = {
elementHandle: $('button'),
bindEventHandlers: function(){
$(this.elementHandle).click(this.showListItemClicked);
},
showListItemClicked: function(){
console.log(listItem.instanceClicked);
}
}

listItem.bindEventHandlers();
button.bindEventHandlers();
</script>


I think I am close but the console log on the showClickedItem() function is returning ''. Like when I initially created the listItem object.

Please find the fiddle here https://jsfiddle.net/rbfaxw12/

Answer

You need to use listItem instead of this in the alertTheContent function as this refers to current element context which invoked the click handler i.e. li not listItem

alertTheContent: function(){
    listItem.instanceClicked = $(this);
    alert(listItem.instanceClicked.html());
}

DEMO

Comments