Using loops to simulate the effects of :hover in Javascript for each child div element, as an

For a while now, I've been utilizing the code below (or something similar) to showcase information on specific posts:

Html:

<div class="main">
<div class="info">
    <div>Words</div>
    <div>Words</div>
     <div>Words</div>
     <div>Words</div>
     <div>Words</div>
</div>

CSS:

.main {
    position:relative;
    background-color:#aaa;
    margin:150px auto 0 auto;
    width:50%;
    height:300px;
}

.info {
    background-color:#ccc;
    position:absolute;
    width:30%;
    top:0;
    left:100%;
    height:100%;
}
.info div {
     position:relative;
     right:100%;
    opacity:0;
    margin:10px 7px 20px 7px;
    transition:all .5s ease-in-out;
}
.main:hover .info div:nth-child(1){
    transition:all .5s ease-in-out;
    right:0;
    opacity:1;
}
.main:hover .info div:nth-child(2){
    transition:all .5s ease-in-out .1s;
    right:0;
    opacity:1;
}
.main:hover .info div:nth-child(3){
    transition:all .5s ease-in-out .2s;
    right:0;
    opacity:1;
}
.main:hover .info div:nth-child(4){
    transition:all .5s ease-in-out .3s;
    right:0;
    opacity:1;
}
.main:hover .info div:nth-child(n + 4){
    transition:all .5s ease-in-out .4s;
    right:0;
    opacity:1;
}

My goal is to find a solution that will work regardless of the number of divs within the info div. For instance, if there were 50 divs, I would like each one to display .1s later than the previous. The current example has a fixed number of divs within .info, but in my intended application, the number of divs could vary greatly - it could be 50 or none.

Therefore, I'm looking for a potential Javascript solution that can handle different amounts of divs and replace my existing CSS transition code.

Answer №1

Check out this code snippet: http://codepen.io/Leth0_/pen/lhwfE

$(".main").mouseover(function(){
  var x = 200;
  $(".info").children().each(function(){    
    $(this).delay(x).fadeIn(x).animate({"right":"0%"},"slow").css({opacity:1});    
  x = x + 200;
  });
});
$(".main").mouseout(function(){
  var x = 200;
  $(".info").children().each(function(){    
    $(this).delay(x).animate({"right":"100%"},"slow").fadeOut(x+200)    
  x = x + 200;
  });
});

I recommend giving this pen a try, it seems to align with what you are looking for. There might be some issues if you rapidly move in and out of the container, but I will work on fixing that. Stay tuned for updates.

Answer №2

To apply CSS transition effects to multiple div elements, I recommend using JavaScript to set the transition properties when the document is ready:

let allDivs;
document.addEventListener("DOMContentLoaded", function() { //Execute when the document has loaded
    allDivs = document.getElementById("content").children;
    
    for (let i = 0; i < allDivs.length; i++) {
        if (allDivs[i] instanceof HTMLDivElement) {
            allDivs[i].style.transition = "all .3s ease-in-out "+(i/2)+"s"; //Adjust timing accordingly
        }
    }
});

You can view an example in this code snippet: http://jsfiddle.net/UniqueCoder/example/

Answer №3

It's not necessary for the elements to be child nodes when using :hover, but based on your code and what you're trying to achieve, I believe this solution is quite effective.

CSS

.main:hover .info div{
    transition-property:all;
    transition-timing-function:ease-in-out;
    transition-duration:.5s;
    right:0;
    opacity:1;
}

After adding your posts, you can then do:

JS

$('.main:hover .info div').css('transition-delay',function(index){
     if(index>=4){
         return '.4s'
     }
     else{
       return index*0.1+'s'
    }
})

This approach offloads the animation burden from your JS code, improving performance by leveraging CSS for animations whenever possible.

If you prefer a purely JavaScript solution, you could try something like:

$('baseElement').on('mouseenter','.main',function(event){
           $($(event.target).find('.info div)).animate({});//add your desired animation here
    });

    $('baseElement').on('mouseleave','.main',function(event){
          $($(event.target).find('.info div)).animate({});//reset to initial state
    })

However, I advise against this method as it involves additional processing and suboptimal animations, tying DOM manipulation too closely to JavaScript events, which can complicate debugging as your project grows.

Answer №4

In my opinion, sticking to CSS is the way to go for this task. It's all about style and presentation, so CSS is a perfect fit. Plus, you won't need to rely on JavaScript for any animations.

When it comes to the CSS code itself, there's room for improvement to make it easier to maintain. Here's an example:

.container {
    position: relative;
    background-color: #f2f2f2;
    margin: 50px auto 0 auto;
    width: 70%;
    height: 400px;
}

.sidebar {
    background-color: #eaeaea;
    position: absolute;
    width: 25%;
    top: 0;
    left: 100%;
    height: 100%;
}
.sidebar div {
    position: relative;
    right: 80%;
    opacity: 0;
    margin: 10px 5px 15px 5px;
    transition: all .3s ease-in-out;
}
.container:hover .sidebar div {
    right: 0;
    opacity: 1;
}
.container:hover .sidebar div:nth-child(2){
    transition-delay: .1s;
}
.container:hover .sidebar div:nth-child(3){
    transition-delay: .2s;
}
.container:hover .sidebar div:nth-child(4){
    transition-delay: .3s;
}
.container:hover .sidebar div:nth-child(n + 4){
    transition-delay: .4s;
}

If the CSS starts to get overwhelming, another option could be using JavaScript to directly manipulate the transition-delay property instead.

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

Here's a guide on how to display texts underneath icons in Buttons using Material UI

Currently, this is the Button I have displayed https://i.sstatic.net/YkHp0.png I am trying to figure out how to position the Dummy Button text beneath the icon. Can someone assist me with this? Below is my code snippet: <Button className={classes.d ...

Seeking insight on the implementation of the next() function in expressjs

I'm struggling to understand the concept of the next() method in express.js. I'm curious if next() is exclusive to express.js. Another question that comes to mind is, in the code snippet below, what exactly does next() do? Does it move to the fol ...

Using Bootstrap v4 to create an Inline Select with Text

Currently seeking an inline dropdown styled with Bootstrap v4 that resembles the following: https://i.sstatic.net/ZTs8b.gif I have experimented with several options, and so far the closest one is as follows: <div class="dropdown"> <button cla ...

Can you please provide me with information on how I can send messages to US numbers using a toll-free number?

I attempted to utilize this code in the SNS console, but it showed a failure. I am seeking guidance on how to send a message using a TFN number. async sendMessage(testId: number) { const mobileNo = test.customer.phoneNo; const params = { Message: ...

Converting audio information into a string format using Flask, followed by decoding it using Javascript

I have created a Python Flask application with the functionality displayed below. Here, I am utilizing Azure text to speech to synthesize voice from text. @app.route("/retrieve_speech", methods=['POST']) def retrieve_speech(): text= ...

Preserving the top line or heading while cutting through a table

In my HTML, I have a table with the following structure: <table id="table"> <tr> <td>ID</td> <td>Place</td> <td>Population</td> </t ...

Is it possible to apply two ngClass directives to a single div element in Angular 4?

When I click to start editing, a component is called for the editing process. In this component, I am unable to click on anything and the background turns black, which is okay. However, I would like for each ID that I select to edit to become active with a ...

Navigating the complexities of integrating Angular-based JS select/input values using CefSharp Offscreen on an external website: A comprehensive guide

I have encountered some challenges with setting input values on a third-party webpage that utilizes Angular for field validation. When attempting to set the value attribute using Chrome or CefSharp, the value does not update as expected. To work around th ...

Implementing context menus on the Material-UI DataGrid is a straightforward process that can enhance the user experience

I am looking to enhance my context menus to be more like what is demonstrated here: Currently, I have only been able to achieve something similar to this example: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx The contextmenu ...

Sending selected option from bootstrap dropdown to the subsequent php page

Is there a way to pass the selected value from a dropdown in Bootstrap to the next page? I have multiple options to choose from and I don't want to create separate pages with the same layout for each option. How can I pass the dropdown value to the ne ...

Comparing HTML5 and web services with MVC3

Within my organization, there is an ongoing discussion regarding the best approach to developing our future web applications. We currently have two distinct groups of developers who share common interests. All parties agree on utilizing html5, css3, and jQ ...

Tips for retrieving specific values from drop-down menus that have been incorporated into a dynamically-sized HTML table

How can I retrieve individual values from dropdown menus in HTML? These values are stored in a table of unspecified size and I want to calculate the total price of the selected drinks. Additionally, I need the code to be able to compute the price of any ne ...

"Tempus Dominus now offering a seamless experience without the need for an

The example code provided seems to be malfunctioning: <button id="idbtn"> $('#idbtn').datetimepicker(); ...

"Encountering issues with getJson function when used on a web hosting

Issue with Web Service JSON Connection: http://mohamedbadr.com/webservice/list.php File Fetching Results: http://contestlancer.com/web/getList.php Code for Getlist file: <!DOCTYPE HTML> <html> <head> <title>Hotel Promotion ...

Tips for effectively engaging with a Component's aggregationUnleash the full potential of

After configuring an aggregation for my Component, here is what it looks like: aggregations : { busyDialog : { type: "sap.m.BusyDialog", multiple: false } } The aggregation is named ...

What advantages does JWT have over Firebase that make it the preferred choice?

In our authentication systems, we have the option to verify a user through Firebase or by their stored email in the database. Despite having these methods of verification, why do we incorporate JWT (json web token) into our processes? What distinct advan ...

What could be causing the absence of pagination links on my website?

While attempting to adjust the width of the images, I noticed that the navigation pager below (pages 1,2,3) unexpectedly disappeared. As a CSS beginner, I'm unsure why this happened and how to resolve it. The code for the navigation is still present, ...

Ensure to include three parameters in your AJAX request using jQuery

I've encountered an issue while trying to pass 4 parameters in an ajax call using jQuery. The first parameter works fine, but the other three do not. var share_nid = $('.share_class').attr('share_nid'); var share_type ...

Exploring JSON data using Jquery

My goal is to extract data from a JSON feed and create two arrays, then calculate the average value of both arrays. The process starts by creating arrays as follows: $.getJSON('jasonfile.json', function(rawdata) { var array_one = []; var arr ...

Issue with integrating Bootstrap into Angular 2

When attempting to link to the bootstrap.css file located in the node_modules folder within index.html, I encountered an error. The application's folder structure is as follows: ecommerce-app/node_modules ecommerce-app/src/app/index.html All attem ...