Skip to content Skip to sidebar Skip to footer

Auto Scroll Div Based On Mouse Position

I want to automatically scroll a div based on mouse position using jQuery. If you see this fiddle here, you can see a number of images that are horizontally ordered in a div that i

Solution 1:

A slightly different way to achieve what you need:

jQuery(function($) {

  $(window).load(function() {

    var $gal = $("#propertyThumbnails"),
      galW = $gal.outerWidth(true),
      galSW = $gal[0].scrollWidth,
      wDiff = (galSW / galW) - 1, // widths difference ratio
      mPadd = 60, // Mousemove Padding
      damp = 20, // Mousemove response softness
      mX = 0, // Real mouse position
      mX2 = 0, // Modified mouse position
      posX = 0,
      mmAA = galW - (mPadd * 2), // The mousemove available area
      mmAAr = (galW / mmAA); // get available mousemove fidderence ratio

    $gal.mousemove(function(e) {
      mX = e.pageX - $(this).offset().left;
      mX2 = Math.min(Math.max(0, mX - mPadd), mmAA) * mmAAr;
    });

    setInterval(function() {
      posX += (mX2 - posX) / damp; // zeno's paradox equation "catching delay"	
      $gal.scrollLeft(posX * wDiff);
    }, 10);

  });

});
#parent {
  position: relative;
  margin: 0 auto;
  width: 60%;
  height: 260px;
}

#propertyThumbnails {
  position: relative;
  overflow: hidden;
  background: #444;
  width: 100%;
  height: 262px;
  white-space: nowrap;
}

#propertyThumbnailsimg {
  vertical-align: middle;
  height: 100%;
  display: inline;
  margin-left: -4px;
}
<divid="parent"><divid="propertyThumbnails"><imgsrc="//placehold.it/600x400/0bf" /><imgsrc="//placehold.it/600x400/f0b" /><imgsrc="//placehold.it/600x400/0fb" /><imgsrc="//placehold.it/600x400/b0f" /><imgsrc="//placehold.it/600x400/bf0" /></div></div><scriptsrc="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

where mPadd is the area (in PX, at the left and right border zone) without any sensitivity to prevent user frustrations :)

Solution 2:

this should at least get you headed in the right direction.

var parent = $('#parent');
var img = $('img:first-child');

parent.on('mousemove', function(e) {
    mouseX = e.pageX
    img.css('margin-left',-mouseX/parent.width()*100);

});

http://jsfiddle.net/xWcXt/4/

Post a Comment for "Auto Scroll Div Based On Mouse Position"