Search code examples
javascriptjqueryhtmlcssdraggable

How can i drag a moving image using JQuery?


Hello i am new to JQuery or java actually i am newbie at programming!!! I did basic tutorial of jQUERY and making a game using Jquery. I am stuck at one thing and also not sure if my code is correct anyway here is my code..

var b = function($b, speed) {
    var beeWidth = $b.width();

    $b.animate({
        "right": "90%",
        "left": "90%"
    }, speed, function() {
        $b.animate({
            "left": 0 - beeWidth + "px"
        }, speed, function() {
            b($b, speed);
        });
    });

};
$(function() {
    b($("#b"), 5000);
    b($("#bOne"), 4500);
    b($("#bTwo"), 4000);
    b($("#bThree"), 3500);
    b($("#bfour"), 3000);
    b($("#bfive"), 2500);
    b($("#bsix"), 2000);
    b($("#bseven"), 1500);
});
body * {
  display: block;
}
body {
    background-image: url("...");
}

img{
  width: 150px;
  height: 75px;
  position:relative;
  display:inline-grid;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<img id="b" src="http://www.clker.com/cliparts/s/o/o/A/x/F/bee-md.png">
<img id="bOne" src="http://www.clker.com/cliparts/s/o/o/A/x/F/bee-md.png">
<img id="bTwo" src="http://www.clker.com/cliparts/s/o/o/A/x/F/bee-md.png">
<img id="bThree" src="http://www.clker.com/cliparts/s/o/o/A/x/F/bee-md.png">
<img id="bfour" src="http://www.clker.com/cliparts/s/o/o/A/x/F/bee-md.png">
<img id="bfive" src="http://www.clker.com/cliparts/s/o/o/A/x/F/bee-md.png">
<img id="bsix" src="http://www.clker.com/cliparts/s/o/o/A/x/F/bee-md.png">
<img id="bseven" src="http://www.clker.com/cliparts/s/o/o/A/x/F/bee-md.png">


Solution

  • Yes you can ! you should just use jQuery UI .

    $(function(){
      $( "#draggable" ).draggable();
    });
    #draggable{
      width: 100px;
      height: 100px;
      background: #000;
      color: #FFF
    }
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    
    <div id="draggable">
      I AM DRAGGABLE
    </div>