Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend an onclick action on a button with JQuery

Tags:

jquery

I have a button that already has an onclick-event and an assigned function. I wish to add another function call in front of it. I can imagine it should be possible to fiddle around with the onclick attribute (attr), but I do not think this is best practice.

What would you consider best practice to prepend a function call on an existing onclick-event?

like image 619
Niels Brinch Avatar asked Apr 16 '12 06:04

Niels Brinch


People also ask

What is prepend function in jQuery?

The prepend() method inserts specified content at the beginning of the selected elements. Tip: To insert content at the end of the selected elements, use the append() method.

How to click on button in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.


3 Answers

If you are not afraid to mess with the guts of jQuery:

// "prepend event" functionality as a jQuery plugin
$.fn.extend({
  prependEvent: function (event, handler) {
    return this.each(function () {
      var events = $(this).data("events"), 
          currentHandler;

      if (events && events[event].length > 0) {
        currentHandler = events[event][0].handler;
        events[event][0].handler = function () {
          handler.apply(this, arguments);
          currentHandler.apply(this, arguments);
        }      
      }
    });
  }
});

$("#someElement").prependEvent("click", function () {
    whatever();
});​

See it live: http://jsfiddle.net/Tomalak/JtY7H/1/

Note that there must already be a currentHandler or the function will not do anything.

Disclaimer: I consider this a hack. It depends on jQuery internals that might change in the next version of the library. It works now (I tested jQuery 1.7.2), but don't be surprised if it breaks with a future version of jQuery.

like image 195
Tomalak Avatar answered Oct 13 '22 09:10

Tomalak


I've written a short example here:

​$("button").click(function() { // this is already existing
    if ($("span").length) {
        alert("ok");
    }
});

var clicks = $("button").data("events").click.slice();
$("button")
    .unbind("click")
    .click(function() { // this is the new one which should be prepended
        $("body").append($("<span>"));
    });
$.each(clicks, function(i, v) {
    $("button").click(v);
});

like image 23
noob Avatar answered Oct 13 '22 09:10

noob


I don't think there's a way to prepend a function call on an existing onclick event, however you can try this:

$('#foo').unbind('click');
$('#foo').click(function() { 
   // do new function call..
   // call original function again...
});

Hope that helps.

like image 22
marknatividad Avatar answered Oct 13 '22 09:10

marknatividad