Can you tell me if there is a switch available for hover or mouse enter/mouse leave functions?

I have a series of div elements, each containing several nested div elements. I would like to add hover effects to these div elements. However, I am unsure whether to use the hover or mouseenter function. For instance, when hovering over a div, I want it to animate and move to the left or change color. The issue is that the effect persists even when moving the mouse elsewhere, which is not what I desire. I want it to behave like CSS hover, reverting back after the mouse leaves. DEMO

Below is my code:

$(document).ready(function(){
    $(".close").hide();
    $(".ln, .gw, .mc, .rt").hover(function(){
        var classname = $(this).parent();
        var name = $(classname).children(':first-child').next();

        $(name).animate({
            "margin-left": "100px"                        
         }, 500);

        $(classname).find(".close").fadeIn(500);
    });
});

HTML Code

<div class="item1">
    <div class="name1 ln">name 1</div>
    <div class="name2 ln">name 2</div>
    <div class="name3 ln">name 3</div>
    <div class="close">close</div>
</div>
<div class="item2">
    <div class="name4 gw">name 1</div>
    <div class="name5 gw">name 2</div>
    <div class="name6 gw">name 3</div>
    <div class="close">close</div>
</div>
<div class="item3">
    <div class="name7 mc">name 1</div>
    <div class="name8 mc">name 2</div>
    <div class="name9 mc">name 3</div>
    <div class="close mc">close</div>
</div>
<div class="item4">
    <div class="name10 rt">name 1</div>
    <div class="name11 rt">name 2</div>
    <div class="name12 rt">name 3</div>
    <div class="close">close</div>
</div>

Any suggestions for improvement?

Answer №1

If given the opportunity, I would implement the following jQuery code:

 $(document).ready(function(){
    $(".close").hide();
    $(".ln, .gw, .mc, .rt").hover(function(){
        var classname = $(this).parent();
        var name = $(classname).children(':first-child').next();

        $(name).stop();
        $(name).animate({
            "margin-left": "100px"                        
         }, 500);

        $(classname).find(".close").stop();
        $(classname).find(".close").fadeIn(500);
    }, function(){
        var classname = $(this).parent();
        var name = $(classname).children(':first-child').next();

        $(name).stop();
        $(name).animate({
            "margin-left": "0px"                        
         }, 500);

        $(classname).find(".close").stop();
        $(classname).find(".close").fadeOut(500);
    });
});

This piece of code has been tweaked for efficiency and better functionality.

Answer №2

If you want to target each item individually, you can start by adding a new class to all items called .item. Then, you can use jQuery to manipulate the second div within each item. Here's an example code snippet that you can try:

$(".item").each(function(){
    $(this).find('div').eq(1).hover(function(){
      var name = $(this);
      $(this).toggleClass('active');
      if($(this).hasClass('active')){
          $(name).stop().animate({
           "margin-left": "100px"                        
          }, 500);
        } else {
          $(name).stop().animate({
           "margin-left": "0"                        
          }, 500);
        }
      $(this).parent().find(".close").stop(true,true).fadeToggle(500);
    })
})

Feel free to check out this Demo Fiddle for a visual representation.

Answer №3

Implement a callback function for dynamic behavior

$(document).ready(function(){
    $(".close").hide();
    $(".ln, .gw, .mc, .rt").hover(function () {
        console.log('working');
        var classname = $(this).parent();
        var name = $(classname).children(':first-child').next();

        $(name).stop().animate({
            "margin-left": "100px"                        
         }, 500);

        $(classname).find(".close").fadeIn(500);
    }, function () {
        console.log('workign2');
        var classname = $(this).parent();
        var name = $(classname).children(':first-child').next();

        $(name).stop().animate({
            "margin-left": "0px"                        
         }, 500);
        $(classname).find(".close").fadeOut(500);
    });

View the live demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with the Jquery bounce animation

Just starting out with Jquery and trying to incorporate a bounce effect into my application. I came across a sample code here that works perfectly. However, when I copied and saved the code on my system, I encountered a JS error: Object does not support me ...

The filtering feature in AngularJS ng-options is not functioning correctly

Greetings, I am a newcomer to angular. In my current demo application, I have created a list of users with a select filter using ng-option. There seems to be a bug that I have been unable to identify. The issue: When I select the Female option, i ...

How can I combine HTML and CSS in a single request using the sendFile method in Express?

const app = require('express')(); app.get('/', function(req, res) { res.sendFile(__dirname + "/" + "index.html"); }); <link rel="stylesheet" href="style.css"> I utilized the Node.js code above to send an HTML file. In order to ...

Using JavaScript to create a search bar: Can "no results found" only show after the user has completed typing their search query?

How can I ensure that the "no match" message only appears after the user has finished typing in their search query, rather than seeing it while they are still typing "De" and the list displays "Demi"? usernameInput.addEventListener("keyup",function(){ ...

what is the process for configuring a Universal link using javascript?

I have taken all the necessary steps to utilize a universal link. I created an AASA file, verified it using aasa-validator, and configured it in XCODE as required. Now, I am facing the challenge of setting up a hyperlink on my webpage that can redirect us ...

Conceal the Download Button Effectively

I operate a website for playing audio files and I am looking to prevent users from downloading the sounds using the download button in the HTML audio element. Here is what I came up with: <audio src="sound.mp3" controls controlsList="nodownload">< ...

Is it possible to have a getter in vuex dynamically update when another getter's value changes?

Within my vuex store, I have this getter that retrieves authority_count: authority_count (state, getters) { return getters.dataView?.getUint16(4, true) || state.pack.authority_count; } I want authority_count to default to state.pack.authority_count ...

What occurs when you use the statement "import someModuleName from someModule" in JavaScript?

When reusing a module in multiple places, you typically use module.exports = yourModuleClassName to make the module exportable. Then, when you want to use it elsewhere, you can simply import it with import yourModuleClassName from 'yourmodulePath&apos ...

Angular error ReferenceError: $Value is not defined in this context

As a newcomer to AngularJS, I am facing an issue while passing a list from the HTML file to the backend for processing. The error message ReferenceError: $Value is not defined keeps popping up. Within my controller file, I have a function named test. The ...

Fluid centering of DIV content both vertically and horizontally

Check out this example: When dealing with fluid divs, line height won't work as expected. My current code relies on line-height which doesn't work when the box sizes change. How can I ensure that a link (content) always appears perfectly centere ...

What are the steps to executing a duplicated project in Node.js?

https://github.com/gleitz/mahjong Trying to set up this app on my Windows, following the provided instructions: - First, install dependencies with npm update - Then start the application with node app.js Seems straightforward, so I decided to give it a t ...

Tips for establishing breakpoints within Material UI grid for achieving responsiveness

I am currently utilizing Material ui's Grid component to organize my user interface elements. Here is the code snippet: <Grid container spacing={3}> <Grid container item xs={12} sm={12} md={12} style={{ marginTop: '-1.5%', marginRi ...

Eliminate any blank brackets in a JSON structure

Looking to extract certain elements from a JSON string. Input : "sample": [{},{},{},{},{},{},{}], Output : "sample": [], Attempted solution : var jsonConfig = JSON.stringify(jsonObj); var result = jsonConfig.replace(/[{},]/g, ''); // Global ...

Meta tags are causing issues with HTML5 validation on the website

Striving to enhance the HTML validity of my website, I encountered several errors in the meta tags that are marked as invalid. Unfortunately, I am unsure how to modify them to rectify these errors. <meta http-equiv="X-UA-Compatible" content="IE=edge,ch ...

What is the best way to ensure that the Bootstrap navbar remains collapsed at all times, regardless of the size of the

Is there a way to keep my Bootstrap navbar constantly collapsed regardless of the screen size? I'm currently using Bootstrap, and I've noticed that when the screen is larger, the navbar expands automatically. What can I do to ensure that the navb ...

Unable to invoke functions in the child window

In my Vue page, I have a script that opens a child window using the code snippet below: this.presentation = window.open( this.$router.resolve({name:'presentation'}).href, 'child window', 'width=auto,height=auto' ) ...

Need help with styling for disabled autocomplete? Check out the attached image

I'm currently working with material-ui and react to create a basic form. Everything is functioning properly except for a small UI issue that I can't seem to figure out how to resolve. When I utilize the browser's auto-complete feature, the i ...

Explore the hidden route of the input components

HTML: <div id="quiz"> <div id="question"> <p id="quiz-txt">What is your favorite color?</p> <ul id="quiz-opt"> <div id="ans"> <input type="checkbox" id="Red" value="Red" class="options"> ...

Received an empty response while making an AJAX request - ERR_EMPTY_RESPONSE

I am trying to fetch real-time data from my database using Ajax, but I keep encountering an error. Here is the code snippet: <script> window.setInterval( function() { checkCustomer(); //additional checks.... }, 1000); function che ...

Unusual body padding found in the mobile design

When visiting on a mobile device and inspecting the elements in Google Chrome, try disabling the style rule overflow-x: hidden from the body element and then resizing the window. You may notice a white vertical stripe (padding) appearing on the right side ...