duongntbk
duongntbk

Reputation: 670

Pass event object to trigger function in firefox

This is the MCVE of the problem I'm having. Let say I have this very simple test page:

<html>
<header>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
        function testMethod(e){
            alert(e.target.id);
        }
        $(document).ready(function(){
            $("#btn_test").on("click", testMethod, event);           
        });
    </script>
</header>
<body>
    <input type="button" id="btn_test" value="OK" />
</body>
</html>

You can find the jsfiddle here.

In Chrome or IE, when I push the button, the id will be displayed in a message box. But in Firefox since window.event is not defined, I cannot bind testMethod to the button's onclick event.

I know that if I'm writting it inline, I can pass the event like this:

onclick="testMethod(event)"

But how can I pass event to my function in Firefox without writing it inline?

Upvotes: 2

Views: 1287

Answers (3)

sbsatter
sbsatter

Reputation: 581

If you refer to the jQuery Reference here, you'll notice that the third parameter has to be the handler. So, simply remove the third parameter and pass the handler to achieve this.

Check out the demo fiddle here.

<body>
    <input type="button" id="btn_test" value="OK" />
</body>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
        function testMethod(e){
            alert(e.target.id);
        }
        $(document).ready(function(){
            $("#btn_test").on("click", testMethod);           
        });
    </script>

Upvotes: 0

Max Koretskyi
Max Koretskyi

Reputation: 105489

Usually, when you subscribe to an event using on or addEventListener, the event object is passed as a parameter to a callback. You never have to pass it explicitly when you register your callback. So this will do:

$("#btn_test").on("click", testMethod);

The problem with your code on Firefox is that there is no global event property and you get an error:

ReferenceError: event is not defined

and your event subscription never gets registered.

Upvotes: 1

PenAndPapers
PenAndPapers

Reputation: 2108

remove the the 3rd parameter it works on firefox.

$("#btn_test").on("click", testMethod);

Upvotes: 1

Related Questions