jQuery Mouseenter and Mouseleave Trigger Examples Javascript

jQuery is undoubtedly the most useful JavaScript library. We can use jQuery to complete the tedious tasks faster with less number of lines. It is widely used for handling events such as clicks, mouseenter, mouseleave, touch events, etc.

I see people are still using old methods to handle mouse events. So, I would like to share the latest methods to handle such events.

Mouseenter Example

It is a simple javascript program that triggers the mouseenter event for the selected element. Here all the elements with the class name “button” are selected. It will print a message in the console when the user moves the mouse pointer to one of the selected elements.

$(document).ready(function () {
    $(".button").mouseenter(function () {
        console.log("You moved the pointer to the button")
    })
})

Mouseenter Example 2 With Old Method

This method still works and is very useful for handling events when you want to trigger events only on a particular child element. For example, assume you like to trigger the event only if the mouse enters the button inside the div tag. You can easily achieve that using the below method.

$(document).ready(function () {
    $("div").on("mouseenter", "button", (function () {
        console.log("You moved the pointer to the button inside the div")
    }))
})

Mouseleave Example

It works the same as the mouseenter method. The method will trigger the event whenever the user moves the mouse pointer away from the element.

$(document).ready(function () {
    $(".button").mouseleave(function() {
        console.log("You moved the pointer away from the button")
    })
})

Mouseleave Example 2 With Old Method

You can use this method if you want to trigger the event only when the mouse leaves the particular child element of the selected jQuery element.

$(document).ready(function () {
    $("div").on("mouseleave", "button", (function () {
        console.log("You moved the pointer away from the button inside the div")
    }))
})