cj333
cj333

Reputation: 2609

jquery mouse scroll change div position

How can I use the mouse scroll event to control a div's position?

I have 12 lis where only 5 of them are visible at any time. I want to be able to show different li elements when the scroll wheel scrolls. If possible, I'd like this in a circular layout.

I don't want scroll my page, but something like a gallery. If you imagine all my li elements as photos, if the mouse is scrolled the photos change position in the horizontal direction, something like http://viralpatel.net/blogs/demo/javascript-mouse-scroll-wheel-event.html

I need to do this with jQuery and horizontally, not with vanilla JS in the vertical. Is there a plugin or some working code?

fiddle

<script src="jquery.js"></script>

<script>
    $(document).ready(function() {
       //jQuery code
    });
</script>

<style>
    * { padding: 0; margin: 0; }
    div, ul { height: 100px; width: 500px; display: block; overflow: hidden; }
    div { position: relative; }
    ul { position: absolute; }
    li { float: left; height: 98px; width: 98px; display: block; list-style: none; border: 1px solid #aaa; }
</style>

<div>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>10</li>
        <li>11</li>
        <li>12</li>
    </ul>
</div>

Upvotes: 0

Views: 16098

Answers (1)

Terry
Terry

Reputation: 14219

I'm having a bit of trouble figuring out what you're actually looking for. If you want jQuery tools to assist with scrolling you can use these:

http://api.jquery.com/scroll/ - Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.

http://api.jquery.com/scrollTop/ - Get the current vertical position of the scroll bar for the first element in the set of matched elements.

You can control the position of an element during scroll by using those methods.

<div id="myDiv" style="position: absolute" />

$(window).scroll(function() {
    $('#myDiv').css('top', $(window).scrollTop() + 'px')
});

However part of your question makes it sound like you want to show 5 list items and when they scroll show 5 more using AJAX ("and if possible, I would like a circle show."). This is similar to the 'endless scrolling' concept which Twitter and other sites use. There are a bunch of plugins for this, one of them can be found here.

Edit:

Using the jQuery mousewheel plugin by Brandon Aaron you can do something like:

CSS:

*{padding:0;margin:0;}
div { height:120px; width:500px; display:block; overflow:auto; }
ul { width: 9999px; }
li { float:left; height:98px; width:98px; display:block; list-style:none; border:1px solid #aaa;}

Javascript:

$('div').mousewheel(function(event, delta) {
  this.scrollLeft -= (delta * 30);
  event.preventDefault();  // Prevent the window from scrolling
});

Upvotes: 4

Related Questions