2

I would like to trigger a mouseup event programmatically given:

<div id="abc">Click me</div>

<script>
    document.getElementById('abc').addEventListener('mouseup', function () {
        alert('mouseup');
    });
</script>

Now, to trigger I've tried the following:

document.getElementById('abc').onmouseup();

Or with jQuery

$('#x').trigger('mouseup');

None of these result in an alert so I must be doing something wrong here.

DEMO

UPDATE: Fixed type with addEventListener

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333
  • 1
    `document.getElementById('abc').addEventListener('mouseup', function () { alert('mouseup'); });` It seems you forgot to add the id param in the getElementById func. [Check here](http://jsfiddle.net/cUCWn/86/) – Arsalan Oct 09 '16 at 19:09
  • in the code you pasted the id of the element you want to target is missing, also on your demo you call an ' onmouseup ' method without passing any callback function, if you have a look at the console you can see an error, although the code in your demo works fine without that line of code – jrod Oct 09 '16 at 19:27

2 Answers2

3

getElementById doesn't have a call and an argument in the code below.

document.getElementById.addEventListener('mouseup', function () {
    alert('mouseup');
});

right example

document.getElementById("the id of the element").addEventListener('mouseup', function () {
    alert('mouseup');
});

and if you want to trigger the event not by the mouse but with code, there is already an answer in this link How to trigger event in JavaScript?

Community
  • 1
  • 1
Ali Somay
  • 585
  • 8
  • 20
3

<div id="abc">Click me</div>

<script> document.getElementById.addEventListener('mouseup', function () { alert('mouseup'); }); </script>

getElementById missing the param here i.e getElementById('abc')

document.getElementById('abc').onmouseup();

onmouseup() is not a function its an Event attributes and should be called on some element.

$('#x').trigger('mouseup');

Should be done something like this :

$( "#abc" ).click(function() { $( "#x" ).mouseup(); });

Arsalan
  • 461
  • 3
  • 12