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>

4 Answers 4

3

I think you want this:

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

jQuery([selector]) returns an array.

Sign up to request clarification or add additional context in comments.

Comments

0

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

$('#button').on('click mousedown', function() {
    // do something
});

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.