4

hi to all i have an interesting question

is it possible to copy onclick event of an element like this

$('#ElementId').attr('OldOnClick',$('#ElementId').attr('OnClick'));

Please guide me if there is any way of doing this.

i am trying to disable click event of all elements present on form at some point and on some other point i have to recover them so i am trying to save their onclick with other attribute name

rahul
  • 7,573
  • 7
  • 39
  • 53
  • What are you looking to do exactly? There's no reason that copying the attribute as above shouldn't work. Expecting it to do anything is a totally different story though. You should also be avoiding inline handlers. – Matt Whipple Oct 20 '12 at 12:05
  • i am trying to disable all click event of element present on form at some point and on some other point i have to recover them so i am trying to save their onclick with other attribute name – rahul Oct 20 '12 at 12:07
  • Have you tried just using the same approach you provided as an example? – Matt Whipple Oct 20 '12 at 12:25
  • yes and it's not working instead it's firing onclick of each element – rahul Oct 20 '12 at 12:26
  • It will fire `onclick`, that's what it's supposed to do. If you remove onclick it shouldn't fire, so you're not expressing what you're looking for clearly. For your use case it sounds like you'd be better off doing something like attaching to `$form.on("click"...)` and then doing a check within the handler and conditionally doing `event.preventDefault();`. This may have issues with the inline js depending on the browser though. – Matt Whipple Oct 20 '12 at 13:23

6 Answers6

5

yes, you can access handler functions. The way of doing it in jquery would be this:

$('#specialbutton').click(function(){ console.log("peaches");};

var handlerFunction = $('#specialbutton').data("events").click[0].handler;

$('#specialbutton').click(); // "peaches"
handlerFunction(); // "peaches"

you would then assign it to another element like this:

$('#otherelement').click(handlerFunction);
$('#otherelement').click(); // "peaches"
ChuckE
  • 5,610
  • 4
  • 31
  • 59
  • i want to copy onclick event to the same element with diff. attribute name please read my question properly – rahul Oct 20 '12 at 12:11
  • @rahul - once you get the handle to your click handler using `.data("events").click[0].handler`, you can copy it to wherever you want. For ex: you can do `$('#specialbutton').data('copied', handlerFunction);` – techfoobar Oct 20 '12 at 12:27
  • Not working for me, but the other example below. As $('#specialbutton').data("events") is empty, although jquery click event is bound. – perhelion Feb 27 '18 at 23:46
3

I have written jQuery plugin for copying events. Though, it only works with dynamically added events, but not those added with "on" function.

I hope this will help someone.

Parameters:

eventType - "click", "mouseover" etc.

destination - either jQuery object, dom element or selector

clearCurrent - if true it will clear current handlers at destination - default false

    (function($){
            $.fn.copyEventTo = function(eventType, destination, clearCurrent) {
            var events = [];
            this.each(function(){
                var allEvents = jQuery._data(this, "events");
                if (typeof allEvents === "object") {
                    var thoseEvents = allEvents[eventType];
                    if (typeof thoseEvents === "object") {
                        for (var i = 0; i<thoseEvents.length; i++){
                            events.push(allEvents[eventType][i].handler);
                        }           
                    }
                }
            });
            if (typeof destination === "string") {
                destination = $(destination);
            } else if (typeof destination === "object") {
                if (typeof destination.tagName === "string") {
                    destination = $(destination);
                }
            }
            if (clearCurrent === true) destination.off(eventType);
            destination.each(function(){
                for(var i = 0; i<events.length; i++) {
                    destination.bind(eventType, events[i]); 
                }
            });
            return this;
        }
    })(jQuery);
Flash
  • 466
  • 6
  • 16
1

Here another way:

//sw Get Element
var button = document.getElementById("mybutton");
//sw Get Click Function
var clickFunction = jQuery._data(button, "events").click[0].handler;
//sw Test Click Function
clickFunction();
//sw Copy ClickFunction to another Element
$('#anotherButton').click(clickFunction);

NOTE: The previous code, works with:

$("#mybutton").click(function() {
    //sw TODO HERE
});
swmiguel
  • 11
  • 3
0

It sounds like you may be missing the second line from below. You'd be looking to do a move while you're doing a copy.

$('#ElementId').attr('oldonclick', $('#ElementId').attr('onclick') )
               .removeAttr('onclick');
Matt Whipple
  • 7,034
  • 1
  • 23
  • 34
0

Following will remove the "onclick" store in data of the element and allow you to use it later from the data. Example using A tags

DEMO http://jsfiddle.net/u4eVW/1/

/* remove "onclick" and store */
$('a').each(function() {
    var onclick = $(this).attr('onclick')
    $(this).data('oldClick', onclick)
    $(this).removeAttr('onclick')

})

/* initialize handlers from data */
$('a').click(function() {
        eval($(this).data('oldClick'))
 }) 

If you wish to change something within the individual "onclick" you need to treat the attribute value as a string and use regex methods to modify.

<a href="#" onclick="alert('foo')"> Link 1</a>

var onclick=$(selector).attr('onclick').replace('foo', 'bar')
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

Apparently you shouldn't be able to do this anymore,

this is how you can do it anyway (thanks to this answer):

var handlerFunction = jQuery._data( $('#ElementId').get(0), "events" ).click[0].handler;

and then, as in ChuckE's answer:

$('#otherelement').click(handlerFunction);
$('#otherelement').click(); // "peaches"

don't tell anyone...

SanThee
  • 2,301
  • 3
  • 23
  • 35