Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 566
Jeanluca Scaljeri Avatar asked May 23 '26 07:05

Jeanluca Scaljeri


2 Answers

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?

like image 188
Ali Somay Avatar answered May 25 '26 23:05

Ali Somay


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

like image 45
Arsalan Avatar answered May 25 '26 22:05

Arsalan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!