`Many jquery animations with fading in effect`

I'm interested in creating a smooth fade-in effect for multiple boxes aligned horizontally one after the next. Let's assume each box belongs to the fadeable class and has a unique id. I'd like the boxes to fade from the outside in, resembling something like this:

_ _ _ _ _ _ _ _ _
+_ _ _ _ _ _ _ _
+_ _ _ _ _ _ _ +
+ + _ _ _ _ _ _ +
+ + _ _ _ _ _ + +
+ + + _ _ _ _ + +

and so on. What's the most efficient way to achieve this using jQuery?

Currently, my approach involves assigning an auto-incrementing metadata id boxid to each box div and implementing the following:

max = $(".fadeable:last").attr('boxid');
for(i=0; i<max; i++)
{ 
    $("[boxid=" + i + "]").fadeIn('fast');
    $("[boxid=" + (max-i) + "]").fadeIn('fast');
}

Is there a smoother or more optimized method to accomplish this? For example, utilizing animation or queuing techniques? Additionally, what would be the best practice for arranging these elements in CSS?

Thank you!

Answer №1

Try experimenting with this code snippet:

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript">

            function generateElements()
            {
                for(var id = 0; id < 15; id++)
                {
                    var el = document.createElement('div');
                    $(el).attr('rel', id);
                    $(el).attr('class', 'fadeable');
                    $(el).css('opacity', '0.0');
                    $(el).css('display', 'inline');
                    $(el).css('background', 'green');
                    $(el).css('float', 'left');
                    $(el).css('margin-right', '5px');
                    $(el).text(id);
                    document.getElementById('container').appendChild(el);
                }
            }

            function fadeElements()
            {
                var max = $(".fadeable:last").attr('rel');
                var timer = 0;
                var command = "";
                for(i=0;i<max;i++)
                {
                    command = "$('.fadeable[rel=" + i + "]').fadeTo('slow', 1.0);";
                    command += "$('.fadeable[rel=" + (max-i) + "]').fadeTo('slow', 1.0);";
                    window.setTimeout(command, timer);
                    timer += 1000;
                }
            }
        </script>
    </head>
    <body>                        
        <button onclick="generateElements()" value="Generate Elements">Generate Elements</button>
        <button onclick="fadeElements()" value="Fade Elements">Fade Elements</button>
        <div id="container" style="background:blue;height:200px;width:300px">
            <!--div rel="1" class="fadeable" style="opacity:0.0;display:inline;background:green;float:left;margin-right:5px;">1</div>
            <div rel="2" class="fadeable" style="opacity:0.0;display:inline;background:green;float;left;margin-right:5px;">2</div>
            <div rel="3" class="fadeable" style="opacity:0.0;display:inline;background:green;float:left;margin-right:5px;">3</div>
            <div rel="4" class="fadeable" style="opacity:0.0;display:inline;background:green;float:left;margin-right:5px;">4</div>
            <div rel="5" class="fadeable" style="opacity:0.0;display:inline;background:green;float:left;margin-right:5px;">5</div>
            <div rel="6" class="fadeable" style="opacity:0.0;display:inline;background:green;float:left;margin-right:5px;">6</div>
            <div rel="7" class="fadeable" style="opacity:0.0;display:inline;background:green;float:left;margin-right:5px;">7</div>
            <div rel="8" class="fadeable" style="opacity:0.0;display:inline;background:green;float:left;margin-right:5px;">8</div>
            <div rel="9" class="fadeable" style="opacity:0.0;display:inline;background:green;float:left;margin-right:5px;">9</div>
            <div rel="10" class="fadeable" style="opacity:0.0;display:inline;background:green;float:left;margin-right:5px;">10</div-->
        </div>
   </body>
</html>

Answer №2

It seems like your question has led to a significant amount of research! Allow me to present my findings. I have optimized the solution in a jQuery plugin style, which includes some additional code for flexibility and reusability across your project. You also have the option to set fadeIn to false, causing it to fade out in a similar fashion:

<!DOCTYPE html >
<html>
<head>
<style type="text/css" media="screen">
  #items { height:50px; text-align: center; line-height: 50px; }
  #items div {
    width: 50px; height: 50px;
    float: left; position: relative;
    background: red;
    opacity: 0.0; -moz-opacity: 0.0; filter:alpha(opacity=0);
  }
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script type="text/javascript" charset="utf-8">
  $.fn.fadeFromOutside = function(opts){
    if(this.size() > 0){
      var options = options = $.extend({}, $.fn.fadeFromOutside.defaults, opts),
        size    = this.size(),
        steps   = Math.ceil(size / 2), // Always round up
        fade_in = options.fadeIn,
        time    = options.length,
        wait    = Math.floor(time / steps), // Delay between fades
        items   = this.css({opacity: (fade_in ? 0.0 : 1.0)}),
        fade_to = (fade_in ? 1.0 : 0.0); // Decide final opacity

      // Using private internal function for processing and delayed fadeIn.
      var fade_action = function(one, two, count_left, delay){

        var callback = null;
        if( options.complete && count_left == (steps - 1))
          callback = options.complete;

        $(one).animate({opacity: fade_to}, {duration: time, complete: callback});
        
        if(one != two) 
          $(two).animate({opacity: fade_to}, time);

        if(count_left < steps){
          window.setTimeout(function(){
            fade_action(
              items.get(count_left), 
              items.get(size - 1 - count_left), 
              count_left + 1,
              delay);
          }, delay);
        }
      }

      // Initiate the fade
      fade_action(items.get(0), items.get(size - 1), 1, wait);

    }
    return this; // Maintain chain
  }

  $.fn.fadeFromOutside.defaults = {
    fadeIn: true,
    length: 1000
  }

  /* DOM Ready */
  $(function(){
    $("#items > div").fadeFromOutside({
      fadeIn: true,
      length: 2000,
      complete: function(){ 
        alert('done!');
      }
    });
  });
</script>

</head>

<body>
<div id="items">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
</div>
</body>
</html>

If the elements initially have display:none or require fading out to end with display:none, use the following command to trigger the plugin:

// For fadeIn when divs start as display:none
$("#items > div")
  .css({display: block, opacity: 0.0})
  .fadeFromOutside();

// For fadeOut to hide all divs at the end
$("#items > div")
  .fadeFromOutside({
    complete: function(){ $("#items > div").hide() }
  });
});

Answer №3

$(".fadeable").forEach(function() {
    $(this).show('fast');
});

Answer №4

If you slightly modify your original code, you can achieve the desired effect:

    let totalBoxes = $(".fadeable:last").attr('boxid');
    for(let i=0; i<totalBoxes; i++)
    { 
        $("[boxid=" + i + "]").fadeIn('fast', function(){
            $("[boxid=" + (totalBoxes-i) + "]").fadeIn('fast');
        });

    }

While this might not provide the exact functionality you're looking for, the concept is to link the fading animations so that each element waits for the previous one to finish before starting.

You can accomplish this by using the callback feature in the fadeIn method.

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

What is the best approach for choosing unquoted HTML attribute values?

I have a unique situation where I am dynamically appending a select element to a form from a hidden field, with escaped spaces in the element content. This is the hidden field content: <input type="hidden" id="field1" name="field1" value="<select i ...

As soon as I shrink the browser window, the HTML content becomes restricted and the div elements elegantly slide across the

Encountering this issue for the second time has been quite perplexing. Initially, I attributed it to my lack of experience in the field as a rookie intern when seeking assistance from colleagues at work with no luck in resolving it. The problem arises when ...

Chrome clipping positioned spans

Having trouble positioning a label above inline sections with spans in Chrome, as the labels are getting clipped oddly. Check out these screenshots: Firefox view: Chrome view: In the Chrome screenshot, you can see that the labels are being cut off based ...

Canvg | Is there a way to customize canvas elements while converting from SVG?

Recently, I encountered an issue with styling SVG graphics dynamically generated from data. The SVG graphic appears like this: https://i.sstatic.net/xvIpE.png To address the problem, I turned to Canvg in hopes of converting the SVG into an image or PDF us ...

What are the Functions of Ctrl-K on Stack Overflow?

I'm intrigued by how to incorporate the Ctrl+K (code sample) feature for code. For example: public static void main(String args[]){ System.out.println.out("welcome"); } Is there a way to nicely format this? Do we need any specific package to ...

Reacting to the dynamic removal of spaces

Is there a way to dynamically remove the space between removed chips and older chips in Material-UI when deleting one of them? <div className="row contactsContainer"> {contacts.map((contac ...

Tips for dynamically adding a style property to an element with ng-class in AngularJS

How can I dynamically change the color of a CSS class after using ng-class and add a property to an existing CSS class? <style> customcss:after{ border-top: 7px solid green; } </style> I want to be able to change the color dynamically using ...

Toggling display of divs with jQuery using plus and minus icons

Is it possible to use two different icons as a sprite image for when the show and hide functions are active on a div element? For instance, having a + icon displayed when showing the div, and then switching to a - icon when hiding it. The current code I ...

Utilizing $routeProvider to handle different views within an application

I've successfully developed an Angular Project and implemented $routeProvider for routing. function config($routeProvider, $locationProvider) { $routeProvider .when('/', { controller: 'HomeController', ...

Whenever I attempt to retrieve JSON data, I keep receiving an [object object] alert

When I try to retrieve JSON data from an online server instead of localhost, I'm encountering an [object object] alert. The code works perfectly on localhost. Here is the ASPX code: $(document).ready(function () { $('#btnGetEmployee&a ...

Step-by-step guide on adding and removing a row from a table with the help of jquery and node js

I just finished creating a table in jade that includes two select boxes and a single text box. However, I encountered an issue where my row addition functionality stops working after the user makes a selection in the first select box and then changes the ...

JSF RichFaces dropdown menu for selecting locales with flag icons

After searching for a solution for quite some time, I have yet to find a suitable answer. I am currently working on a JSF web application using the RichFaces library. The application supports multiple locales, allowing users to change them by selecting fro ...

The background image spanning across the entire screen, not just confined to the center

view image details here Can anyone explain why my background image for the main game is displaying like this? I want to set it for the entire screen as I have different backgrounds planned for the menu of the game and the game itself. Any suggestions to ma ...

Choosing siblings of a particular element that meet certain criteria

I am faced with the following situation: <table> <tr class="header"> <tr class="data1"> <tr class="data2"> <tr class="data3"> <tr class="header"> <tr class="data1"> <tr class="data2"> </tabl ...

Correct the string based on a character error

When I have text to display in HTML, for example: var htmlStr = "1.first thing %10-15%. 2.second thing %25-44%. 3.third" And I want to display it in a div: $('#div1').html(htmlStr); However, when I display it in a DIV1 in HTML5 on a mobile pho ...

Creating a unique tab spacing effect using HTML and CSS

I'm currently working on my personal website and I'm looking to create a tab-like effect (similar to word processors) for showcasing projects along with their descriptions. Here's an example layout: ReallyLong NameProject Project1 Descr ...

Adjust the dimensions of an SVG element using CSS within an li element's ::before pseudo-element

I'm working on a list where SVGs are loaded as list items. How can I adjust the height and width of the ::before pseudo-element to be 30px x 30px? Setting the height and width directly didn't work for me. Can someone assist with this? <div cl ...

Parallel ajax function

After creating a form for registering new accounts, I wanted to ensure that the chosen email is available by checking it against a webservice. However, this process takes a few seconds. Let's take a look at the method used: function validateEmail(ema ...

What is the process for inserting an "inline image" in a form prior to uploading it?

I am looking to implement a feature that allows users to write a post and seamlessly upload images within the content, similar to a CMS blog post. Writing the file upload script is straightforward, but creating functionality for an "inline" image placement ...

How do I use jQuery to remove a dynamically added class from the page's header?

When using an inline editor to modify css classes, I encounter the need to remove and then re-add a class definition after making changes. Additionally, users have the option to delete elements, so it's important that the definition is also deleted. ...