jeff jeff -4 years ago 73
Javascript Question

Why does event.target inside jquery does not work

Following is the code, I was trying to place. It is very simple yet the event.target does not fire whereas other normal event handlers work.



$(function($){

var container = $('#container');

function init() {
container.on('click', open)
}

function open() {

if(event.target === container) {
alert ("hi");
}
}

init();

})(jQuery);

body, html {
padding:0;
margin:0;
}

#container {
height: 500px;
width:800px;
margin:0 auto;
background-color:#444;
}

h1{
color:white;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id = "container">
<h1>Testing</h1>
</div>





First problem is that, TypeError: $(…). is not a function

The second problem is that although it works in google chrome, it still shows the above error.

The third error is that, although the function runs in the browser, it does not work when I place, event.target === container command. However, if I simply console.log event.target, it returns me the div id of container. However, when I add that check of the event.target, it stops working.

I am stuck, could anyone help me with an explanation of why this problem occurs

Thanks

Answer Source
  1. Both the values are not referring to same Object Reference in javascript.

$('#container') is a jQuery Object and to get the HTML DOM object you need to retrieve the zeroth element in the Jquery Object. Whereas the event.Target return the HTML DOM element. What you are trying to do is to compare different Objects and hence that condition never passes.

$('#container') is an ID selector and can return multiple matching elements (same ID for more than one element in the HTML), so you need to get the zeroth element returned by Jquery Object. Jquery Object is an wrapper around the HTML Element and includes additional Property and methods.

  1. Remove the $ from $(function($){, it is basically an IIFE Pattern.

So, you need to modify your code as mentioned below.

(function($){
  
  var container = $('#container');
  
  function init() {
    container.on('click', open)
  }
  
  function open() {
    if(event.target === container[0]) {
      alert ("hi");
    }  
  }
  
      init();

})(jQuery);
body, html {
  padding:0;
  margin:0;
}

#container {
  height: 500px;
  width:800px;
  margin:0 auto;
  background-color:#444;
}

h1{
  color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id = "container">
  <h1>Testing</h1>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download