0

I have a function that hides and shows divs on scroll based on pageY position, but I also need the ability to have it automatically hide and show divs in order(only the ones with children), sort of like a fake animated Gif, looping forever.

I tried this:

function autoPlay() {
  $('.conP').each(function(){
    if ($(this).children().length > 0) {
      setInterval(function(){
        $(this).show().delay('100').hide();
      },300);
    }
  });
}

which is not returning any errors, but it's not hiding or showing any of the divs with class="conP".

Any suggestions as to what I'm doing wrong/how I could improve this?

mmm
  • 2,272
  • 3
  • 25
  • 41

4 Answers4

1

try this -

function autoPlay() {
  $('.conP').each(function(){
    if ($(this).children().length > 0) {
      var $that = $(this);
      setInterval(function(){
        $that.show().delay('100').hide();
      },300);
    }
  });
}
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
  • You were totally right, as was NikitaBaksalyar, "this" wasn't selecting each conP, however the problem now is that it's not actually animating :/ It's just setting all divs with conP to display:none, or display:block at the same time. – mmm Jun 12 '13 at 22:24
1

Not sure it's a great idea to run intervals inside loops, but I'm guessing the issue is scope inside the interval function :

function autoPlay() {
    $('.conP').each(function(i, elem){
        if ( $(elem).children().length ) {
            setInterval(function(){
                $(elem).show().delay(100).hide();
            },300);
        }
    });
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

You have an incorrect reference to this in your setInterval closure. Refer to "How this works" in JavaScript Garden.

In your case you should save the reference to this in a variable:

$('.conP').each(function() {
    var $element = $(this);

    setInterval(function () {
        $(element).show().delay('100').hide();
    }, 300);
});

Or, better use the first argument passed to each, which is equal to $(this) in this case.

NikitaBaksalyar
  • 2,414
  • 1
  • 24
  • 27
0

I really appreciate all the help guys, I seem to have figured out the animation part:

setInterval( function() {
    autoPlay();
},120);

function autoPlay() {
    var backImg = $('#outterLax div:first');
    backImg.hide();
    backImg.remove();
    $('#outterLax').append(backImg);
    backImg.show();
}

By hiding whichever div is first, and removing it from-then appending it back into-the containing div, and showing the new first div, it animates quite nicely!

mmm
  • 2,272
  • 3
  • 25
  • 41