Combustion007
Combustion007

Reputation: 474

Is it possible to bind a custom function instead of an event to a div in JQuery?

I wonder if this is possible, I was able to do this with AS3. Is it possible to bind a listener on div that only listens for mouse events. So lets say I have a div called "lion", typically this is how a mouse event is bind:

  $("#mouse").bind("click", function(e)
  {
     alert(e.currentTarget.id);
  }

But as you can see, the mouse event has already been declared as "click". What I would like to do is write a function and then bind that function to "lion" the div. And when lion encounters such mouse events then function is able to capture the mouse event type. Here is the function:

  $.fn.chkType = function(e)
  {
    var evt = e.type;
    var str = "";

    switch(evt)
    {
      case "mouseover":
      str = "MOUSE OVER";
      break;

      case "mouseout":
      str = "MOUSE OUT";
      break;

      case "click":
      str = "CLICK";
      break;

      default:
      break;
   }

   alert(str);
  }

And now if I would like to assign this function to "lion", I am not certain how would this be possible? I have done a lot search and the closest I came was at:

http://api.jquery.com/bind/

I would appreciate your input. Thank you.

Upvotes: 0

Views: 167

Answers (2)

Kevin B
Kevin B

Reputation: 95022

I would suggest binding to all of the events that you want to bind to.

$("#mouse").bind("click mouseover mouseout", function(e) {
    //alert(e.currentTarget.id);
    //alert(e.type);
    console.log(this.id);
    console.log(e.currentTarget.id);
    console.log(e.type);
});

Update
What was the purpose of the $.chkType method? why not just alert the type directly?

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227270

You can make your own custom events, and bind them to elements. You can even bind the same function to multiple events. (P.S. In jQuery 1.7+, use on instead of bind)

$("#mouse").on("lion click", function(e){
    alert(e.type);
});

Now #mouse has a lion event attached to it. Obviously, the browser cannot trigger this event, but you can.

$("#mouse").trigger('lion');​

This will trigger your custom lion event.

DEMO: http://jsfiddle.net/bav4K/2/

NOTE: $.fn is used to attach functions to jQuery objects. In your case that doesn't make much sense (you're not gonna call $('#mouse').chkType()), I'd suggest using $.chkType instead.

Upvotes: 0

Related Questions