user1491819
user1491819

Reputation: 1830

How do I reassign a Javascript event using jQuery?

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>

Upvotes: 2

Views: 1158

Answers (4)

Justice Fist
Justice Fist

Reputation: 111

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

Upvotes: 0

xdazz
xdazz

Reputation: 160883

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.

Upvotes: 0

Jeremy Danyow
Jeremy Danyow

Reputation: 26406

I think you want this:

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

jQuery([selector]) returns an array.

Upvotes: 3

Ja͢ck
Ja͢ck

Reputation: 173642

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

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

Upvotes: 0

Related Questions