Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29139

Trigger mouse-up programmatically

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

Upvotes: 3

Views: 6083

Answers (2)

Arsalan
Arsalan

Reputation: 471

<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(); });

Upvotes: 3

Ali Somay
Ali Somay

Reputation: 625

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?

Upvotes: 3

Related Questions