msmith1114
msmith1114

Reputation: 3241

jQuery Button Click 'this'

Say we have a simple event button handler:

$( "#aButton" ).click(function() {
   console.log( "tile" + this.val() + "clicked" );
});

I realize that "this" is most contexts would refer to the "window" object.....but everywhere i've been looking at code examples of "this" talks about Jquery being a special case, where this is implied to be whatever object the event handler was on (Which i've always thought this was based on whatever "called" the function, and the "Window" is what called the function?

If this simply isn't true for jQuery, is there a better way around referring to the object that was clicked on?

Upvotes: 1

Views: 126

Answers (3)

Pankaj Shukla
Pankaj Shukla

Reputation: 2672

The object that you clicked can be referred by this, so saying this.id will give you button's id "aButton". However, if you want to use jQuery's methods then you have to say $(this).attr('id') which will again give you "aButton". So you do have different mechanisms available to you but if you are using jQuery, it is preferable to use jQuery methods.

Upvotes: 1

Toby Mellor
Toby Mellor

Reputation: 8215

Use $(this) to obtain the clicked element.

$("#aButton").click(function() {
    console.log("tile " + $(this).val() + " clicked");
});

In addition, you can note that $(this)[0] === this

this should can be used when using built in JavaScript methods, such as .addEventListener(). Using this in this context will return the Node that triggered the event.

Upvotes: 2

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

this is the raw DOM element. You have to wrap it in a jQuery object if you want to use jQuery functions on it.

console.log( "tile" + $(this).val() + "clicked" );
//                    ^^^^^^^^^^^^^

Inputs have a property called value that does the same. So you can use it on raw DOM inputs like this:

console.log( "tile" + this.value + "clicked" );
//                    ^^^^^^^^^^

Upvotes: 2

Related Questions