Search code examples
javascriptjqueryeachdelaywait

Get Data Atribute while looping through class elements


I am currenly in the process of learning javascript and one of my tasks is to loop through all divs with a particular class name and show/hide them one by one with a catch where the timing for every div is different and the correct value is stored in the data-attribute tag in every div with that particular class name.

window.onload = function(){
   alpha();
}

function alpha(){
    var dataAttribute = 1000;
    $(".element").each($).wait(dataAttribute, function(){
        $(this).show().delay(dataAttribute).queue(function(){
            $(this).hide();
        });
    });
}
.element{
  display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://creativecouple.github.io/jquery-timing/jquery-timing.js"></script>

<div class="element" data-attribute="1000">One</div>
<div class="element" data-attribute="2000">Two</div>
<div class="element" data-attribute="3000">Three</div>
<div class="element" data-attribute="4000">Four</div>
<div class="element" data-attribute="5000">Five</div>

My initial idea for solving this problem was to replace the dataAttribute variable with $(this).data("attribute"), but if I do that the .wait property stops working. However, this method works perfectly fine with the .delay property. I would be extremely grateful if someone could help me and explain what I am doing wrong. (Also, if I can get rid of the additional timing library that would be a major bonus, but without it I was not able to loop through the classes after some sort of delay.


Solution

  • You can use something like this:

    function alpha(i = 0) {
        var element = $(".element:eq(" + i + ")");
        var time = parseInt(element.attr("data-attribute"));
        element.show().wait(time, function() {
            $(this).hide();
            i++;
            if (i < ($(".element").length))
                alpha(i);
        });
    }