How to use .on and .hover in jQuery ?
jQuery .on() method: This method is used to attach an event listener to an element. This method is equivalent to the addEventListener in vanilla JavaScript.
Syntax:
$(element).on(event, childSelector, data, function)
Parameter
- event: It specifies the event to attach (click, submit, etc.).
- childSelector: It is optional parameter and it specify the specific child to which given event handler can be used.
- data: It specifies optional data to be passed along with function.
- function: It specifies the function to be run while the attached event triggered.
Example:
<!DOCTYPE html> < html > < head > <!-- Adding jQuery Library --> < script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js" > </ script > < style > /* Adding basic styling */ div { background-color: green; width: 100px; height: 100px; color: #fff; text-align: center; } </ style > </ head > < body > < div >Normal</ div > < script > $('div').on('click', function () { // Changing the content $(this).html('Clicked!'); }); </ script > </ body > </ html > |
Output:
- Before Clicking on div element:
- After Clicking on div element:
jQuery .hover() method: This method is used to specify the styles of the element during mouseover and mouseout conditions. It takes two functions as an argument:
- mouseoverFunction: Triggers when mouse enters the element.
- mouseoutFunction: Triggers when mouse leaves the element.
You can specify multiple styles inside these functions.
Syntax:
$(element).hover(mouseoverFunction, mouseoutFunction)
Example:
<!DOCTYPE html> < html > < head > <!-- Adding jQuery Library --> < script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js" > </ script > < style > /* Adding basic styling */ div { background-color: green; width: 100px; height: 100px; color: #fff; text-align: center; } </ style > </ head > < body > < div >Normal</ div > < script > $('div').hover(function () { // mouse-in $(this).css("background-color", "blue"); $(this).html('Hovered!'); }, function () { // mouse-out $(this).css("background-color", "green"); $(this).html('Normal'); } ) </ script > </ body > </ html > |
Output:
- Before mouse move over:
- After mouse move over: