Rakim
Rakim

Reputation: 1107

move div using javascript

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><

Upvotes: 0

Views: 14634

Answers (2)

dezman
dezman

Reputation: 19358

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.

Upvotes: 4

Smeegs
Smeegs

Reputation: 9224

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.

Upvotes: 1

Related Questions