восемь восемь - 1 year ago 148
Javascript Question

Moving a DIV with mouse

I'm just creating an own jquery scrollbar which scrolls the content in a div. It's something like jQuery ScrollPane.

Now I came to the point where I need to move the scroll button. My question is, which is the best way to do it without any UI plugin. So when user clicks on the scroll button it can be moved vertically in its parent container with mousedown event. How could I do that?


Answer Source

Here's a starting point, hope that's what you're after:

$(function() {

$.fn.slider = function() {
    return this.each(function() {
        var $el = $(this);
        $el.css('top', 0);
        var dragging = false;
        var startY = 0;
        var startT = 0;
        $el.mousedown(function(ev) {
            dragging = true;
            startY = ev.clientY;
            startT = $el.css('top');
        $(window).mousemove(function(ev) {
            if (dragging) {
                // calculate new top
                var newTop = parseInt(startT) + (ev.clientY - startY);
                //stay in parent
                var maxTop =  $el.parent().height()-$el.height();          
                newTop = newTop<0?0:newTop>maxTop?maxTop:newTop;
                $el.css('top', newTop );
        }).mouseup(function() {
            dragging = false;
    border:1px solid red;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div class="container">
    <div class="slider" />
<div class="container">
  <div class="slider" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download