How can one iterate through elements of a specified length using Jquery?

Currently, I am in the process of designing an animation for my website. The animation involves different divs that each contain an image and a description related to that image within an aside element. The width of the aside is slightly wider than the image, and when hovered over, it slides to the right and expands its width.

The issue arises when hovering over another div, causing the previously hovered one to return to its original position. My initial solution was to loop through all the non-hovered divs, but this resulted in all divs (including the last hovered) triggering the animation simultaneously, leading to a visual bug as the aside is absolutely positioned behind the image. Ideally, only the first div should have the animation effect.

I attempted to refine my approach by looping through non-hovered divs with a defined size (after being shown), but I was unable to make it work. I also struggled to find a solution using the 'each' function to target specific elements.

Below is a snippet of my HTML code:


        <div class="partenaires-wrapper">
        <img src="http://mylor.fr/mauro/wp-content/uploads/2014/08/sharks.png" alt="" width="223" height="138" />
        <div class="partenaires-aside">

        Sed rutrum elementum odio, ut efficitur magna efficitur sit amet. Phasellus posuere eget felis non tempor. Morbi elementum, velit non aliquam suscipit, 
    odio orci viverra felis, sit amet elementum tellus mauris a nunc. 
Aliquam nec nisl eget nunc pulvinar varius commodo id urna. Duis ac sem erat. Pellentesque aliquet posuere justo ac luctus. Aliquam porta placerat blandit.

        </div>

And here is the corresponding Javascript section:


$(".partenaires-aside").mouseover(function () {
                       $(".partenaires-aside").not(this).each(function () {
                                $(this).delay( 800 ).animate({'width':'24%'}, 500);
                                $(this).animate({'margin-left':'0%'}, 500);
                                $(this).find("p").hide("slow"); 
                        });
                        $(this).animate({'margin-left':'30%'}, 500);
                        $(this).animate({'width':'60%'}, 500);
                        $(this).find("p").show("slow");    
                });

If my explanation is unclear, I apologize, and I appreciate any assistance you can provide. Thank you!

Answer №1

Instead of cycling through every div, you can apply a class, let's call it hovered, to the div when hovering over it. Then, when moving to another div, locate the previously hovered div using class=hovered and remove the class with animation. Finally, add class=hovered to the currently hovered element.

Check out the code snippet below -

$(".partenaires-aside").mouseover(function () {
    // Locating previously hovered div using $(".hovered")
    $(".hovered").each(function () {
        $(this).delay( 800 ).animate({'width':'24%'}, 500);
        $(this).animate({'margin-left':'0%'}, 500);
        $(this).find("p").hide("slow");
        // Removing the hovered class
        $(this).removeClass('hovered'); 
    });

    $(this).animate({'margin-left':'30%'}, 500);
    $(this).animate({'width':'60%'}, 500);
    $(this).find("p").show("slow");
    // Adding the hovered class
    $(this).addClass('hovered');     
});

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

inject custom styles into a Material-UI styled component

Although I have come across similar questions, none seem to directly address my current situation. I am in the process of transitioning from MUI v4 to MUI v5 and have encountered various scenarios where a specific style is applied externally. For instance ...

reCAPTCHA v3 - Alert: There are no existing reCAPTCHA clients available

After coming across a similar issue on Stack Overflow (link to the question here), I attempted to implement reCAPTCHA on my website to combat spam emails received through the form. Despite following Google's instructions, I encountered an error that p ...

Challenge with organizing space within a nested layout of flexboxes and CSS grids

Is it possible for my aside element and div.content to evenly split the available space in the container? Additionally, should the grid within div.content take up all the vertical space? The issue I'm encountering is that grid items aren't able ...

Troubleshooting JavaScript within Embedded Resources

Looking for the most effective method of debugging JavaScript in Visual Studio when dealing with embedded resource files? Due to the fact that JavaScript is compiled into a library, setting breakpoints directly on the source file may not yield desired res ...

Tips on showcasing Javascript filter outcomes after at least 2 characters have been entered

Currently, I have implemented a filter search box that displays results as soon as a single letter is inputted. However, due to the large amount of data that needs to be filtered through, I would like the search to only show results when a minimum of two l ...

javascript utilizing key inputs

Is there a way I can create a function that activates when the "A" key on my keyboard is pressed, sending a signal to nupp('/TS'), and stops sending the signal when the "A" key is released? <html> <head> <script src=\"htt ...

Create an input field with a dynamic and exclusive identifier using the DataTables plugin

I am having trouble creating unique IDs for each input field based on the number of rows Here is the code snippet: $(document).ready(function() { var oTable = $('#jsontable').dataTable(); //Initialize the datatable $.ajax({ url ...

Exploring the integration of SQLite in a PhoneGap mobile application

I've been working on a phonegap app and trying to implement sqlite functionality. Despite following a tutorial, it's not functioning properly. Take a look at my code: <script type="text/javascript"> //add listener when device ready docume ...

Having trouble persisting my login status in Selenium using Python

Has anyone experienced issues with logging into Instagram using an automate tab? Previously, I didn't have any problems, but now it seems that Instagram is not allowing users to log in through automation. An error message stating the following appears ...

What is the most effective way to utilize bootstrap classes and their associated functions exclusively for mobile devices by using media queries?

I am encountering an issue with a table in my application that causes the UI to break when the screen width is reduced to less than 600px. To address this, I would like to implement the following bootstrap classes to add a scroll to the application: .tabl ...

Is it possible to change the title of a QGroupBox using HTML expressions in Python?

Does anyone know how to set the title of a QGroupBox with HTML expressions in a Python program? For example, using ABC for subscript. If you have any insights or solutions, please share! Thank you. ...

What is the JavaScript design for creating plugins?

[I'm brand new to the world of Javascript, so please bear with me.] I am developing an application in node.js that will feature a collection of plugins. Each "plugin" will consist of a function, or possibly two, that can manipulate a string in some w ...

Internet Explorer 7 does not support the return link feature when using jQuery

My issue involves using jQuery and Ajax, where my Ajax.php file outputs a specific field into the main file. Everything works as expected when I click in Mozilla and Chrome, resulting in an alert pop-up. However, when attempting the same action in Internet ...

What distinctions are there between saving a constant value in a variable and in state?

There are a couple of different approaches to accomplishing the same thing within a React functional component. When you have a config value that is only needed inside the component (just a constant value, never passed in or modified), you can either use a ...

What steps can be taken to stop Internet Explorer from interfering with a hover trigger on a child element?

I'm encountering an issue with my HTML and CSS code that seems to work perfectly in all browsers except for IE10 and below. The problem arises on a user profile page where there is a profile picture (avatar). When hovering over the avatar, the CSS tr ...

JavaScript/jQuery countdown timer failing to initialize properly

Having some trouble with a countdown timer that I customized from the original version. The issue seems to be with startCountdown(startDate,deadlineDate,expiredText) as it's returning undefined. Any thoughts on what might be causing this? All relevan ...

What scenarios call for utilizing "dangerouslySetInnerHTML" in my React code?

I am struggling to grasp the concept of when and why to use the term "dangerous," especially since many programmers incorporate it into their codes. I require clarification on the appropriate usage and still have difficulty understanding, as my exposure ha ...

Is it advisable to save data with ajax by sending large text in the query string or is it better to use a

I am looking to integrate a comment feature into my ASP.NET website inspired by stackoverflow.com. It seems that ajax is being used instead of posting the entire page. How exactly is the value entered in the textarea passed to the server page? Is it thro ...

Creating Interactive Labels with React-Three-Renderer (Example code provided)

Currently, I am utilizing react-three-renderer (npm, github) to construct a scene using three.js. In my project, my objective is to create a label that consistently faces the camera by using <sprite> and <spriteMaterial>, inspired by stemkoski ...

What steps are involved in uploading data to serve as a filter while running a PHP script to retrieve data from an SQL database?

Currently, I am retrieving data from a PHP file using miniAjax. The code snippet below demonstrates how the process begins: microAjax("genjsonphp.php", function(data) { var json = JSON.parse(data); var points = json; //code continues In the c ...