Skip to content Skip to sidebar Skip to footer

Simulating Onclick Event With Javascript

What i am trying to do is to put an imagebutton in div which is wider than the button itself and when the outside div is clicked, i want the image button onclick() function to be c

Solution 1:

What you've missed is the fact that some events bubble up the document tree triggering all click handlers of parent elements. To stop it, call stopPropagation on the event object.

<inputtype="button" onclick="event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true);alert('button clicked');"id="addButton"/>

(in old IE there is no stopPropagation, you need to set event.cancelBubble=true)

Solution 2:

In Internet Explorer, you can simply do

myElement.click();

However, the W3 standard is a bit more complex. The following code should work for other browsers:

var evt = document.createEvent("HTMLEvents");
evt.initEvent("click", true, true);
myElement.dispatchEvent(evt);

See also this question: How can I simulate a click to an anchor tag?

Solution 3:

use window.event.stopPropagation(); like

<div style="width: 200px; border: 1px solid red;" onclick="alert('div clicked');(document.getElementById('addButton')).click();">
    <input type="button" value="X" onclick="alert('button clicked');window.event.stopPropagation();"id="addButton"/>
</div>

Solution 4:

you need to avoid the event bubbling from Javascript like so :

<html><body><scripttype="text/javascript">functionclickOnDiv(e){
            alert('Div clicked.');
            document.getElementById('addButton').click();
            e.preventDefault();
            returnfalse;
        }

    functionclickOnButton(e){
        e.preventDefault();

        // This line to prevent event bubbling
        e.stopPropagation() ? e.stopPropagation() : (e.cancelBubble=true);

        alert('Button clicked.');
        returnfalse;
    }


    </script><divid='maDiv'style="width: 200px; border: 1px solid red;"><inputtype="button"value="Click Me !"id="addButton"/></div><script>
        (function(){
            document.getElementById('addButton').onclick = clickOnButton;
            document.getElementById('maDiv').onclick = clickOnDiv;
        })();
    </script></body></html>

Tested.. :)

Post a Comment for "Simulating Onclick Event With Javascript"