2

When I log the click handler in js, (var clickHandler = button.onclick;) it gives the following as expected:

clickHandler:function () {
    alert("onclick - original onclick handler");
}

However, when I log the jQuery click handler (var clickHandler = jQuery('#button').click;), I get:

  clickHandler:function (a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)}

Why the difference? How do I get a handle on the function so I can reassign it to another event, eg. onmousedown?

(I need to reassign an existing js event that I have no control over, so it hasn't been added with jQuery).

    <input type="text" name="name_input" id="name_input" />
    <a href="#" id="button">Click</a>
    <script>
        var input = document.getElementById("name_input");
        var button = document.getElementById("button");
        input.onchange = function(event) {
            alert("Change");
        };

        //reassign onclick to onmousedown

        button.onclick = function() {
            alert("onclick - original onclick handler");
        };

        //reassign onmousedown handler
        var clickHandler = button.onclick;
        // var clickHandler = jQuery('#button').click;
        console.log('clickHandler:' + clickHandler);

        button.onmousedown = clickHandler;
    </script>
user1491819
  • 1,790
  • 15
  • 20

4 Answers4

3

I think you want this:

var clickHandler = jQuery('#button')[0].click;

jQuery([selector]) returns an array.

Jeremy Danyow
  • 26,470
  • 12
  • 87
  • 133
0

You can assign the same click handler on more than one event:

$('#button').on('click mousedown', function() {
    // do something
});
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

jQuery('#button').click is just the method used to set the click event handler, it's used as

jQuery('#button').click(event_handler);

But not

jQuery('#button').click = event_handler;

So jQuery('#button').click won't give you the event_handler.

xdazz
  • 158,678
  • 38
  • 247
  • 274
0

The button.onclick is the browsers native implementation of the click handler. See this raw HTML example which shows how to assign a click handler without using script tags. See this link for why this is a bad idea.

When you assign click handlers using jQuery, you're using the jQuery library to assign the click handler function to the button. This is why there was a different output when you printed jQuery('#button').click.

I would suggest that you stick with jQuery only and do not mix with calls to native JavaScript to manipulate events, like button.onclick = function(){};. See here

Community
  • 1
  • 1
Justice Fist
  • 111
  • 4