I have several of these lines on a page:
In my Save() met
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 You can convert this to a jQuery object with Save() function this refers to the DOM element that was clicked.$(this).
This refers to window by default however, so you'll need to pass this as a parameter of the Save function:
<div class="save-button" onclick="Save(this)">Save</div>
function Save(div) { }
now inside Save, you can use div to refer to the div that was clicked.
I was confused about how this behaved. This link helped me: http://www.quirksmode.org/js/this.html
Simply refer to it as: $(this)
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);
});
Pretty straight forward...
$('#myDiv').click(function(){
save($(this));
})
function save($obj){
$obj.css('border', '1px solid red');
}