In jQuery, hover()
method is used to create hover effects on an HTML element. Using hover()
method you can define the actions to occur when the element is hovered over or when the hover state is exited. Here is a simple example :
1. Include Jquery
HTML
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
2. Create HTML Structure
HTML
<div class="hover-element">
<p>Hover over me</p>
</div>
3. Write jQuery Code
JavaScript
<script>
$(document).ready(function(){
$('.hover-element').hover(
function(){
// Code to execute when the mouse enters the element
$(this).css('background-color', '#ffcc00');
},
function(){
// Code to execute when the mouse leaves the element
$(this).css('background-color', ''); // Reset background color
}
);
});
</script>
Note: You can customize the code and add some advanced hover effects by adding more jQuery functions.
4. Advanced Hover Effect
JavaScript
<script>
$(document).ready(function() {
$('.hover-element').hover(
function() {
// Code to run on mouseenter
$(this).animate({
fontSize: '20px', // Increase font size on hover
letterSpacing: '2px' // Add letter spacing on hover
}, 300); // Animation duration in milliseconds
},
function() {
// Code to run on mouseleave
$(this).animate({
fontSize: '16px', // Return to the original font size
letterSpacing: '0px' // Remove letter spacing
}, 300);
}
);
});
</script>