How to attach a method to HTML element event using jQuery ?
There are various events like click(), mouseenter(), mouseout(), etc which are available in jQuery. For attaching a method to an HTML elements event, we will need a jQuery method on(), which will help us to attach an event handler to the selected HTML.
on(): This method is used to attach event handlers to the currently selected HTML elements. On the event handler, we can add the method and perform tasks accordingly.
.on( <events> , "<selector>" , <method> )
- event: It accepts one or more jquery events separated by space.
- selector: It can accept the selector to filter out the children of the selected element, if the selector is not passed then it only works on the selected element.
- method: With the help of the method, we can pass the data to the respective event when that event is fired.
CDN link: Add the given link below to the head tag of the HTML file to work with jQuery.
Example 2: In this example, we will attach a method to the div directly to its tag. We can call onmouseenter() event so that when the mouse will enter the HTML div, the size of the div and the size of the font will get smaller as well as the previous method will also work. When we click on the div, the color of the text will also be changed to green.