Friday 15 January 2010

javascript - Make a div move using jquery -



javascript - Make a div move using jquery -

i'm trying create div move of 50px left right every 500 milliseconds next jquery code:

<div id="obj"></div> <script> function move(before){ var howmuch = before + 50; $("#obj").css("margin-left",howmuch + "px"); settimeout(move(howmuch),500); } settimeout(move(0),500); </script> #obj{ background-color:red; width:100px; height:100px; border-radius:10px 10px 10px 10px; -moz-border-radius:10px 10px 10px 10px; -webkit-border-radius:10px 10px 10px 10px; margin-left:0px; }

...

<!doctype html> <head> <meta charset="utf-8"> <title>test</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <div id="obj"></div> <script> function move(before){ var howmuch = before + 50; $("#obj").css("margin-left",howmuch + "px"); settimeout(move(howmuch),500); } settimeout(move(0),500); </script> </body>

but that's not working. when launch firefox or net explorer, box gets huge distance margin (much bigger width of screen), , noticed if run stackoverflow's snippet function box not move. problem?

you code has few mistakes, right way is:

var howmuch = 0; // start @ position 0, here global variable function move(before) { howmuch = before + 50; // add together 50 previous value $("#obj").css("margin-left", howmuch + "px"); // move settimeout(function() { //call next move, executing move function current position after 500ms move(howmuch) }, 500); } settimeout(function() { //start recursive funcion after 500ms, 0 start move(howmuch) }, 500);

class="snippet-code-css lang-css prettyprint-override">#obj { background-color: red; width: 100px; height: 100px; border-radius: 10px 10px 10px 10px; -moz-border-radius: 10px 10px 10px 10px; -webkit-border-radius: 10px 10px 10px 10px; margin-left: 0px; } class="snippet-code-html lang-html prettyprint-override"><!doctype html> <head> <meta charset="utf-8"> <title>test</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <div id="obj"></div> <script> var howmuch = 0; function move(before) { howmuch = before + 50; $("#obj").css("margin-left", howmuch + "px"); settimeout(function() { move(howmuch) }, 500); } settimeout(function() { move(howmuch) }, 500); </script> </body>

javascript jquery html settimeout

No comments:

Post a Comment