1

I need to dynamically attach a function to a div and pass also the event.

It is working in Chrome / IE, but not FireFox.

I am getting the following error in FireFox console: ReferenceError: event is not defined

How can this be solved?

CodePen: https://codepen.io/dsomekh/pen/YrKmaR

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.example{
cursor:pointer;
border:1px solid black;
text-align:center;
}
</style>

<script>
window.onload = function() { 
var div = $( ".example" );
div.click(function() {Test(event);});

}

function Test (event)
{
    alert(event);
}

</script>
<html>
<div class="example">When clicking on this div, you should get an alert with the event details. This does not work in FireFox.</div>
</html>
David Somekh
  • 795
  • 3
  • 12
  • 33
  • This has nothing to do with dynamic elements, but only happens because Firefox doesn't support the global event object. – adeneo Sep 12 '17 at 10:49

2 Answers2

2

Have you tried:

div.on("click",function(e) {Test(e);});
somosluz
  • 46
  • 6
1

Firefox doesn't support the global event object, it needs to have the event passed as an argument

window.onload = function() { 

    var div = $( ".example" );

    div.click(function(event) { // needs to be here
        Test(event);
    });

}

function Test (event){
    alert(event);
}

You could also just reference the function, and do

div.click(Test);

So you'd get

$(function() {
  $(".example").on('click', Test)
});

function Test (event) {
   console.log(event);
}
.example{
cursor:pointer;
border:1px solid black;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example">When clicking on this div, you should get an alert with the event details. This does not work in FireFox.</div>

and that's it

adeneo
  • 312,895
  • 29
  • 395
  • 388