Yarin
Yarin

Reputation: 183939

Trouble handling JQuery Event targets

I'm trying to create a universal handler for my buttons, but the following code doesn't seem to recognize the event targets, and instead spits out the target.toString() == the current page URL?

html:

<a id="button1" href="#"></a>
<a id="button2" href="#"></a>

jquery/javascript:

function myHandler(e) {

   if (e.target == $("#button1")) 
      alert("Button 1 clicked");
   else if (e.target == $("#button2")) 
      alert("Button 2 clicked");
   else
      alert(e.target.toString());
}

$("#button1").click(myHandler);
$("#button2").click(myHandler);

Upvotes: 0

Views: 799

Answers (3)

Kieran
Kieran

Reputation: 233

I've created a demo with jsFiddle - here

and the code from the demo below:

JavaScript:

$(document).ready(function(){

  function eventHandler(e){
    var clicked = $(e.target);

    // will check if element is or is a child of event target        
    if (clicked.is('#btn1') || clicked.parents().is('#btn1'))
      console.log("btn1 was clicked");
    else if(clicked.is('#btn2') || clicked.parents().is('#btn2'))
      console.log("btn2 was clicked");
  }

  $('#btn1').bind('click', function(e){
    eventHandler(e);
    return false;
  });

  $('#btn2').bind('click', function(e){
    eventHandler(e);
    return false;
  });

});

HTML:

<button id="btn1">Button #1</button>
<button id="btn2">Button #2</button>

Hopefully this helps. If you need a non-jQuery version let me know.

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

Two issues with your code.

  1. you missed the # for the ids inside your myHandler.
  2. you are comparing dom elements e.target with jquery objects $('..').

Use

function myHandler(e) {

   if (e.target == $("#button1")[0]) 
      alert("Button 1 clicked");
   else if (e.target == $("#button2")[0]) 
      alert("Button 2 clicked");
   else
      alert(e.target.toString());
}

Upvotes: 2

fcalderan
fcalderan

Reputation:

function myHandler(e) {

   if (e.target.id == "button1")
      alert("Button 1 clicked");
   else if (e.target.id == "button2")
      alert("Button 2 clicked");
   else
      alert(e.target.toString());
}

$("#button1").click(myHandler);
$("#button2").click(myHandler);

your code cannot work because you are comparing the target event with a jQuery object

Live example: http://jsfiddle.net/fcalderan/7b53z/

Upvotes: 3

Related Questions