Reputation:
I did this snippet, so you can have an idea what my real problem is:
$('#test1').on('touchstart mousedown', function(e){
$('#output').val(e.pageY);
});
$('#test2').on('touchstart mousedown', function(e){
$('#test1').trigger('touchstart mousedown');
});
button {
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<button id="test1">test1</button>
<button id="test2">test2</button>
<input type="text" id="output">
As you can see, while clicking button#test1
it outputs the value correctly, but if I need to trigger its action from another element (in this snippet, the button#test2
).. it doesn't work.
I think the e
-event is not being passed through the $.trigger
.
Someone know any trick, or have any ideas? Thanks in advance.
One live fiddle
Upvotes: 2
Views: 153
Reputation: 8165
From the jQuery trigger()
documentation (http://api.jquery.com/trigger/):
The event object is always passed as the first parameter to an event handler. An array of arguments can also be passed to the .trigger() call, and these parameters will be passed along to the handler as well following the event object. As of jQuery 1.6.2, single string or numeric argument can be passed without being wrapped in an array.
For your code, this could look like this:
$('#test1').on('touchstart mousedown', function(e, triggerParam){
$('#output').val(e.pageY || triggerParam);
});
$('#test2').on('touchstart mousedown', function(e){
$('#test1').trigger('touchstart', e.pageY);
});
But in general (and i just mention this, because i think its better practice) to write an extra function, which is called by listeners. Don't let the listener handle the actual action. Better let it delegate to other functions depending on the event.
Quick example using your markup:
function updateOutput( input ) {
$("#output").val(input);
}
$('#test1').on('touchstart mousedown', function(e){
updateOutput(e.pageY);
});
$('#test2').on('touchstart mousedown', function(e){
updateOutput(e.pageY);
});
This way you'll see what each listener and function actually does in a faster and more comprehensive way. Hope it helps.
Upvotes: 1
Reputation: 871
Try this:
$('#test1').on('touchstart mousedown', function(e){
$('#output').val(e.pageY);
});
$('#test2').on('touchstart mousedown', function(e){
$('#test1').trigger(e);
});
Upvotes: 11
Reputation: 833
You want to pass parameter with trigger:
var event = jQuery.Event( "touchstart" );
event.pageY = 999;
$('#test1').trigger(event);
Upvotes: 0