I have several of these lines on a page:
<div class="save-button" onclick="Save()">Save</div>
In my Save()
method I want to manipulate the div that was clicked to call the Save()
method. How do I pass that in (I think $(this)
), without resorting to ids?
Many thanks!
To pass this element to JavaScript onclick function and add a class to that clicked element, we can set the onclick attribute to a function that's called with this . to set the onclick attribute to the a elements to call onClick with this .
You can use addEventListener to pass this to a JavaScript function.
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. Here is the HTML for the examples in this article.
To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.
Either remove the save()
and use click()
to catch the event:
<div class="save-button">Save</div> <script> $('.save-button').click(function () { // Now the div itself as an object is $(this) $(this).text('Saved').css('background', 'yellow'); }); </script>
[ View output ]
Or if you insists on using such function as save()
:
<div onClick="save(this)">Save</div> <script> $(function () { save = function (elm) { // Now the object is $(elm) $(elm).text('Saved').css('background', 'yellow'); }; }); </script>
[ View output ]
EDIT (2015): .on('click', function)
<div class="save-button">Save</div> <script> $('.save-button').on('click', function () { // Now the div itself as an object is $(this) $(this).text('Saved').css('background', 'yellow'); }); </script>
Inside the event handler, this
refers to the clicked element. However, inside the function you call from the event handler, which is Save
, this
will refer to window.
You can explicitly set what this
should refer to inside Save
via call
[MDN] (or apply
):
onclick="Save.call(this, event || window.event);"
then you can use it inside the function as $(this)
:
function Save(event) { // `this` refers to the clicked element // `$(this)` is a jQuery object // `event` is the Event object };
But as you are using jQuery, you really should do
$('.save-button').click(Save);
to bind the event handler. Mixing markup with logic is not a good style. You should separate the presentation from the application logic.
Or if you want Save
to accept an element as parameter, then just pass it:
onclick="Save(this);"
and with jQuery:
$('.save-button').click(function() { Save(this); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With