Added new section about click events (#28286)
Added new section about click events and gathering the element from those events
This commit is contained in:
committed by
Martin Payne
parent
0b878890ad
commit
81f85dc02d
@ -99,6 +99,34 @@ $( document ).on("click", "element", function() {
|
||||
});
|
||||
```
|
||||
|
||||
### Getting The Element From A Click event
|
||||
This applies to both jQuery and plain JavaScript, but if you set up your event trigger to target a class, you can grab the specific element that triggered the element by using the `this` keyword.
|
||||
|
||||
jQuery happens to make it very easy (and multi browser friendly) to traverse the DOM to find that element's parents, siblings, and children, as well.
|
||||
|
||||
Let's say I have a table full of buttons and I want to target the row that button is in, I can simply wrap `this` in a jQuery selector and then get its `parent` and its parent's `parent` like so:
|
||||
|
||||
```javascript
|
||||
$( document ).on("click", ".myCustomBtnClassInATable", function () {
|
||||
var myTableCell = $(this).parent();
|
||||
var myTableRow = myTableCell.parent();
|
||||
var myTableBody = myTableRow.parent();
|
||||
var myTable = myTableBody.parent();
|
||||
|
||||
//you can also chain these all together to get what you want in one line
|
||||
var myTableBody = $(this).parent().parent().parent();
|
||||
});
|
||||
```
|
||||
|
||||
It is also interesting to check out the event data for the click event, which you can grab by passing in any variable name to the function in the click event. You'll most likely see an `e` or `event` in most cases:
|
||||
|
||||
```javascript
|
||||
$( document ).on("click", ".myCustomBtnClassInATable", function (e) {
|
||||
//find out more information about the event variable in the console
|
||||
console.log(e);
|
||||
});
|
||||
```
|
||||
|
||||
#### More Information:
|
||||
|
||||
For more information, please visit the [official website](https://api.jquery.com/click/#click).
|
||||
|
Reference in New Issue
Block a user