0

The problem

I'm trying to create a product card which loop throught images on mouse hover (for desktop) and when the div outside the image is completely inside the viewport on mobile. Also when the mouse is not hovering anymore the loop stops, or when the card is out of the viewport (mobile) the loop stops.

What I've accomplished

I accomplished the desktop devices part but I can't figure out how to do it for mobile devices...

Here's my code

HTML+PHP

<?php for ($i=1; $i < $variable_number ; $i++) { ?>
<div class="card-image waves-effect waves-block waves-light">
                <img id="<?php echo $i; ?>" style="background-image: cover;" src="/images/shop1.jpg" data-alt-src="/images/shop2.jpg;/images/trip1.jpg;/images/trip2.jpg" class="img-loop activator">
                <div style="margin:0;" class="progress white">
                  <div id="load<?php echo $i; ?>" class="determinate black" style="width: 0%"></div>
                </div>
              </div>
<?php
          }
         } ?>

CSS

I'm using the MaterializeCSS framework

Javascript

var alt_src, elem, i, timeout, moving, width=0, loop_interval=2000, loader_num;

$('img.img-loop')
.mouseenter(function() {
  $(this).data('old-src', this.src);
  elem = this;
  alt_src = $(this).data('alt-src').split(';');
  i = 0;
  loader_num = this.id;
  moving = setInterval(move, (alt_src.length+1)*(loop_interval/100));
  timeout = setTimeout(loop, loop_interval);
})
.mouseout(function() {
  clearTimeout(timeout);
  clearInterval(moving);
  width = 0;
  var elem = document.getElementById("load"+loader_num);
  elem.style.width = width + '%';
  this.src = $(this).data('old-src');
});

function loop() {
if (i === alt_src.length) {
  elem.src = $(elem).data('old-src');
  i = 0;
} else {
  elem.src = alt_src[i++];
}
timeout = setTimeout(loop, loop_interval);
}

function move() {
  var elem = document.getElementById("load"+loader_num);
    if (width == 100) {
      width = 0;
    } else {
      width++;
      elem.style.width = width + '%';
    }
}

Conclusions

What can I do now to accomplish the effect? What I'm aiming for is something like this Here's a Fiddle of what I've done by now: https://jsfiddle.net/iacopoermacora/Lytj02za/1/

aynber
  • 22,380
  • 8
  • 50
  • 63

1 Answers1

0

if you find out it is a mobile device you could go through your elements as soon as scroll event has been triggered and then check if one or more of your elements is inside the viewport and then start the carousel animation for these elements:

function isElementInViewport (el) {
    var rect = el[0].getBoundingClientRect();
    return (rect.top>-1 && rect.bottom <= $(window).height());
}

example is from Determine if element is either above or below fold of page

oezzi
  • 82
  • 4