This jQuery tutorial provide a brief introduction how to use hover and click method. The tutorial covers how to display message when hove over an element, get the width and ID of elements being hoved over. This tutorial finally shows how to use click event.

Syntax of jQuery hover event

At first glance jQuery hover event is quite similar to mouseover event. The hover() method will triggers the mouseover event when the mouse pointer is over an element. Usually, a function will be run or binded when the hover event is triggered.

jQuery hover Event Example

The jQuery codes below will display a message in a Textarea field when mouse pointer hove over the cloud element.

// Declare a variable
var targetElement = $("#cloud");

var elementWidth = targetElement.width();

targetElement.hover(function() {
$("#outputText").css( {"color": "#090", "font-size": "16px" } ).text("The width is: " + elementWidth);
});

The result is:

jQuery hover to Get ID of Selected Element

With jQuery codes, the ID of hoved over element can easily be got. The following jQuery codes will get the ID of element being hoved over.

// Declare a variable
var targetElement = $("#cloud");

targetElement.hover(function() {

// Remember to write this code inside the function
var elementName = this.id;

$("#outputText").css( {"color": "#090", "font-size": "16px" } ).text("The name is: " + elementName);

});

The picture below shows that the ID of the cloud will be displayed when mouse pointer is over the selected element.

Now, we got some basic idea how to use hover method. In this jQuery tutorial, we show how to use the click method.

Syntax of jQuery click event

The syntax of jQuery hover event is similar to hover event. The click() method will triggers the click event when an element is clicked. Same as the hover event, a function will be run or binded when the click event is triggered.

jQuery click Event Example

The jQuery codes below will display the ID of selected element in a Textarea field when mouse pointer click on the cloud element. The message in the Textarea field will be removed when mouse leave the selected element.

// Declare a variable
var targetElement = $("#cloud");

targetElement.click(function() {
elementName = this.id;
$("#outputText").css( {"color": "#090", "font-size": "16px" } ).text("The name is: " + elementName);
});

targetElement.mouseout(function() {
$("#outputText").css( {"color": "red", "font-size": "14px" } ).text("");
});

The result is:

This is the end of jQuery hover and click method tutorial.