Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Create draggable objects using javascript

    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 675
    Comment on it

    Hii,

    In this blog i am sharing a simple javascript code for creating draggable objects using mouse event.

    • This code can be used when you want to add animation effect in your static html document and make it more attractive.
    • You can use this feature as your web page background also

    Here's the code,Must go through it to learn how to create draggable objects.

    Html:

    <div class="smiley one"></div>
    	<div class="smiley two"></div>
    	<div class="smiley three"></div>
    	<div class="smiley four"></div>
    	<div class="smiley five"></div>

    jQuery:

    var smiley = $('.smiley');
    	var smileyOne = $('.one');
    	var smileyTwo = $('.two');
    	var smileyThree = $('.three');
    	var smileyFour = $('.four');
    	var smileyFive = $('.five');
    
    
    smileyOne.offset({
        left: 100,
        top: 75,
    });
    smileyTwo.offset({
        left: 147,
        top:435,
    });
    smileyThree.offset({
        left: 1211,
        top: -11,
    });
    smileyFour.offset({
        left: 605,
        top: 129,
    });
    smileyFive.offset({
        left: 1099,
        top: 370,
    });
    
    
    var drag = {
        elem: null,
        x: 0,
        y: 0,
        state: false
    };
    var delta = {
        x: 0,
        y: 0
    };
    
    smiley.mousedown(function(e) {
        if (!drag.state) {
            drag.elem = this;
            drag.x = e.pageX;
            drag.y = e.pageY;
            drag.state = true;
        }
        return false;
    });
    
    
    $(document).mousemove(function(e) {
        if (drag.state) {
           	delta.x = e.pageX - drag.x;
            delta.y = e.pageY - drag.y;
    
            var cur_offset = $(drag.elem).offset();
    
            $(drag.elem).offset({
                left: (cur_offset.left + delta.x),
                top: (cur_offset.top + delta.y)
            });
    
            drag.x = e.pageX;
            drag.y = e.pageY;
        }
    });
    
    $(document).mouseup(function() {
        if (drag.state) {
            drag.state = false;
        }
    });

    Note:  Must include this link in your file

    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    Create draggable objects using javascript

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: