kikix2125
kikix2125

Reputation: 37

if statement in jQuery

Is this the correct jQuery syntax for checking if the div is hidden && has a class of "view"? If it does, then reveal the next hidden div with class "view" after .3 second?

Note it's not currently working though, it fades in ALL hidden divs regardless of the class.

<script type="text/javascript">
            $(function() {
                // Start showing the divs
                showDiv();
            });

            function showDiv() {
                // If there are hidden divs left
                if($('div:hidden').length.hasClass('view')) {
                    // Fade the first of them in
                    $('div:hidden:first').fadeIn();
                    // And wait one second before fading in the next one
                    setTimeout(showDiv, 300);
                }
            }
    </script>

Upvotes: 0

Views: 138

Answers (4)

lbstr
lbstr

Reputation: 2832

// get all hidden divs with a class of view
var $hiddenViewDivs = $('div.view:hidden');
// if there are any...
if ($hiddenViewDivs.length) { 
    // get the first one and invoke fadeIn() on it
    $hiddenViewDivs.first().fadeIn(); 
    // And wait one second before fading in the next one
    setTimeout(showDiv, 300);
}

I'll explain what your code was doing (see my new comments with stars around them):

// **Get the length (count) of all hidden divs and invoke hasClass('view') on that number (will throw an error)**
if($('div:hidden').length.hasClass('view')) {
    // **Get the first hidden div and invoke fadeIn() on it, regardless of if it has a class of view or not**
    $('div:hidden:first').fadeIn();
    // And wait one second before fading in the next one
    setTimeout(showDiv, 300);
}

EDIT (ALTERNATE SOLUTION):

The advantage to this solution is that you don't have to keep looking for $('div.view:hidden') in the DOM. Here, you get it once and appease the performance gods.

function showDiv() {
    var $hiddenViewDivs = $('div.view:hidden');
    var i = 1;
    $hiddenViewDivs.each(function(){
        (function($target){ 
            setTimeout(function(){$target.fadeIn();}, 300*i);
        })($(this));
        i++;
    });
}​

Example: http://jsfiddle.net/lbstr/LdzYm/

Upvotes: 2

SMathew
SMathew

Reputation: 4003

$('div.view:hidden:first').fadeIn(function() {
   setTimeout(showDiv, 300); 
});

You don't need the if. jQuery will take care of that for you.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

How about just $('div.view:hidden').length?

Upvotes: 0

Erik Philips
Erik Philips

Reputation: 54628

Probably a better solution is

if($('div.view:hidden').length) {
  // Fade the first of them in
  $('div.view:hidden:first').fadeIn();
  // And wait one second before fading in the next one
  setTimeout(showDiv, 300);
}

Upvotes: 4

Related Questions