0

I have a div and I am trying to move it right and left on page load using js to create a shaking movement.

My code:

    <script type="text/javascript">
        obj = document.getElementById('hs');            
        obj.style.position='relative';  
        function goRight(){             
            obj.style.right = 10px;
            window.setTimeout(goLeft, 100);
        }
        function goLeft(){
            obj.style.left = 10px;
            window.setTimeout(goRight, 100);
        }
        window.onload =goRight;
    </script>

But it doesn't work. The id of my div is hs.

The html is:

            <div id="hs">
        <h1>hs</h1>
        <hr>
    </div><
5
  • 1
    "it doesn't work" ... classic. Commented Oct 29, 2013 at 20:20
  • have a look at setTimeout and setInterval. You'll want to put some delay in there or this won't work. Commented Oct 29, 2013 at 20:21
  • You could refer to this: stackoverflow.com/questions/8041857/… Commented Oct 29, 2013 at 20:23
  • james I added some delay but still Commented Oct 29, 2013 at 20:25
  • @citykid I don't see why this is bad in this case Commented Oct 29, 2013 at 20:27

2 Answers 2

4

Here you go

obj = document.getElementById('hs');
obj.style.position='relative'; 

function shake(interval) {
    obj.style.right = '10px';
    setTimeout(function(){
        obj.style.right = '0px';
    }, interval);
}

setInterval(function(){
    shake(500);
}, 1000)

Your main issue was that after both the right and left values were set, you weren't changing anything anymore, it was static at left: 10px; right: 10px; you have to keep changing one of those values instead.

Sign up to request clarification or add additional context in comments.

11 Comments

it makes perfect sense the way you implemented it. although there is still no progress...
what do you mean there is no progress?
it did not work. I might try it on another element in my html and see if the problem is somewhere else
I did. And I can see it works... I don't get what is wrong with it.. the div I just created for testing doesn't work either..
you probably need to wrap your code in $(document).ready(function(){...}) Do you get any errors in the console?
|
1

I don't know if this is the main problem, but you need to make the 10px into a string.

obj.style.right = '10px';

for both right and left.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.