abejdaniels
abejdaniels

Reputation: 459

I'm trying to force mouseup event after mousedown

elements[0].onmousedown = function(){
      console.log('screen clicked.');
      simulatemouseuphere;
};

All I need to do is add something in my function that triggers mouseup, even if the user is holding the click button down.

elements[0] is my entire page scope, so anywhere you click, it will trigger.

Upvotes: 3

Views: 4929

Answers (4)

Ruan Mendes
Ruan Mendes

Reputation: 92274

All the ways that are described here depend on how you set up the listener: jQuery, element property.

If you want a robust way that will work regardless of how the event was setup, use How can I trigger a JavaScript event click

elements[0].onmousedown = function(){
    fireEvent(elements[0], 'onmouseup');
};

Notice that you are probably better off wrapping the behavior of the mouseup handler into a function that you can call. Triggering handlers is usually code smell because you don't always know what else you may be triggering when firing events. For example:

function doSomethingOnMouseUp() {
    console.log('something on mouse up');
}

elements[0].onmousedown = function(){
    doSomething();
    doSomethingOnMouseUp();
};

elements[0].onmouseup = doSomethingOnMouseUp;

Upvotes: 0

Adam Jenkins
Adam Jenkins

Reputation: 55643

Just a guess, but instead of firing a mouseup event, perhaps you want to trigger the function that is bound to the mouseup event?

var onMouseUp = function() { 
 /* something */  
};

var onMouseDown = function() { 
 /* something */ 
 onMouseUp.apply(this,arguments); 
};

elements[0].onmousedown = onMouseDown;
elements[0].onmouseup = onMouseUp;

Upvotes: 1

Spacemonkey
Spacemonkey

Reputation: 211

I'm pretty sure you can just call the onmouseup event...

elements[0].onmousedown = function(){
      console.log('screen clicked.');

      elements[0].onmouseup();
};

Keep in mind that when you actually physically stop holding the mouse down though, the mouseup event will be triggered again. (unless in the onmouseup() event you manage that)

Tested quickly, looks like it works: http://jsfiddle.net/cUCWn/40/

Upvotes: 1

klenium
klenium

Reputation: 2607

$("body").on("mousedown", function(e)
{
    e.type = "mouseup";
    $(this).trigger(e);
}).on("mouseup", function(e)
{
    console.info(e);
});

Or: https://stackoverflow.com/a/12724570/2625561

For pure JS: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#Triggering_built-in_events

Upvotes: 0

Related Questions