Reputation: 14176
I am trying to pass the elements "event" into a JavaScript function click using jQuery.
INLINE:
This is easy when doing it directly (inline).
<a href="#" onclick="ToggleMinimize('Hello World', event)">Click Me</a>
USING JQUERY:
But how do you do it using jQuery?
<script type="text/javascript">
<!--
function ToggleMinimize(title, e)
{
// ...various execution code would be here ... //
}
jQuery(window).load(function() {
// How do I "get at" the "event" object for the element & pass it into the function definition?
jQuery(".chatDialog-toggle-button").bind('click', ToggleMinimize);
})
-->
</script>
Thanking you ahead of time!
Upvotes: 0
Views: 2708
Reputation: 20612
Following on from what a lot of the other guys have shown regarding passing data to an event function, there is a specific method for this, you can pass a full object map this way per bind.
Also bare in mind that jQuery normalises the event object before you receive it, so it is a little different, see: http://api.jquery.com/category/events/event-object/
function ToggleMinimize(e) {
// ...various execution code would be here ... //
// e.data contains the data object map
// e.data.msg == "Hello World"
}
jQuery(window).load(function() {
jQuery(".chatDialog-toggle-button").bind('click', {'msg': "Hello World"}, ToggleMinimize);
});
Upvotes: 2
Reputation: 47614
You can do it this way:
$(document).ready(function() {
$('.chatDialog-toggle-button').bind('click', function(event) {
ToggleMinimize(event);
});
});
Upvotes: 0
Reputation: 322562
You can send an anonymous function which executs ToggleMinimize()
:
jQuery(window).load(function() {
jQuery(".chatDialog-toggle-button").bind('click', function(e) {
ToggleMinimize( "Hello World", e);
});
})
or you can have ToggleMinimize
return a function, so you can pass Hello World
into it.
function ToggleMinimize(title) {
return function(e){ alert(title); alert(e.target); }
}
jQuery(window).load(function() {
jQuery(".chatDialog-toggle-button").bind('click', ToggleMinimize( "Hello World") );
})
Upvotes: 1
Reputation: 630579
You don't have to, it's already the first agument, like this:
function ToggleMinimize(e) {
// ...various execution code would be here ... //
}
jQuery(window).load(function() {
jQuery(".chatDialog-toggle-button").bind('click', ToggleMinimize);
});
If you want to also pass a title, then use an anonymous function, like this:
function ToggleMinimize(title, e) {
// ...various execution code would be here ... //
}
jQuery(window).load(function() {
jQuery(".chatDialog-toggle-button").click(function(e) {
ToggleMinimize("some title", e);
});
});
Personally I'd use a data attribute, like this:
<a href="#" class="chatDialog-toggle-button" data-title"Hello World">Click Me</a>
Then access it like this:
function ToggleMinimize(e) {
var title = jQuery(this).data("title");
}
jQuery(window).load(function() {
jQuery(".chatDialog-toggle-button").click(ToggleMinimize);
});
Upvotes: 1