Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving Div Box using javascript

I am trying to create a 300px by 300 px div box that moves a few pixels when the user has their mouse on the box. The only thing is when the div hits the end of the browser size I want it to to start moving the other way and not make the window scroll. Any help would be greatly appreciated.

<div style="left:300px; top:300px; width:300px; height:300px; background:blue;>
</div>

This is oleg's code that I am having trouble running in firefox, am i doing something wrong?

<html>
<head>
<script>
window.onload = function () {
var speed = 10, // the box will move by 10 pixels on every step
direction = 1, // 1 = move right; -1 = move left
boxElement = document.getElementById('theIdOfTheBox');

if (boxElement) {
    boxElement.addEventListener('mouseover', function () {
        // Calculate and store some of the box coordinates:
        var boxLeftPos = boxElement.offsetLeft,
            boxRightPos = boxLeftPos + boxElement.offsetWidth;
        // When right side of the box goes too far - change direction:
        if (boxRightPos > document.body.offsetWidth) {
            direction = -1;
        }
        // When left side of the box goes too far - change direction:
        if (boxLeftPos < 0) {
            direction = 1;
        }
        // Recalculate position:
        boxElement.style.left = (boxLeftPos + speed * direction) + 'px';
    });
 }
};
</script>

<style>
#theIdOfTheBox {
position: absolute;
left:100px;
top:100px;
width:300px;
height:300px;
background:blue;
}
</style>


</head>

<body>
<div id="theIdOfTheBox">box</div>
</body>



</html>
like image 470
Gregwest85 Avatar asked Aug 31 '25 03:08

Gregwest85


2 Answers

Start by creating a couple of variable that keep track of speed and direction:

var speed = 10, // the box will move by 10 pixels on every step
    direction = 1; // 1 moves in the positive direction; -1 vice versa

Then grab a reference to your box and attach an event handler to its "mouseover" event:

var boxElement = document.getElementById('theIdOfTheBox');

if (boxElement) {
    boxElement.addEventListener('mouseover', function () {
        // Calculate and store some of the box coordinates:
        var boxLeftPos = boxElement.offsetLeft,
            boxRightPos = boxLeftPos + boxElement.offsetWidth;
        // When right side of the box goes too far - change direction:
        if (boxRightPos > document.body.offsetWidth) {
            direction = -1;
        }
        // When left side of the box goes too far - change direction:
        if (boxLeftPos < 0) {
            direction = 1;
        }
        // Recalculate position:
        boxElement.style.left = (boxLeftPos + speed * direction) + 'px';
    });
}

All done, here's a jsfiddle for you to play around with.

Mind, however, the position: absolute; in the CSS and the fact that you need to wait for the DOM to load to be able to safely perform the getElementById operation.

If you want to avoid usage of offsets, you may want to parse and manipulate margins or padding of the box instead.

Animation

If you want to animate the movement of your box, you can try CSS animations. Just add the following to the style declaration of your box in the CSS:

-webkit-transition: left 0.3s 0.1s ease-out;

The above code will animate any changes in left property in webkit browsers. You can add other vendor prefixes (and none for compatibility with future releases) to enable animation in other browsers that support it.

EDIT

Regarding your comment with running the script on browser launch:

First of all make sure to wrap the JavaScript code in <script></script> tags if you are embedding it in an HTML page. You can run a validator (e.g. validator.w3.org) to ensure you have a correct document structure.

Secondly, place the code inside those tags as close as possible to the end of the body of your document, i.e. </body>.

You can also wrap the entire JavaScript code in a function that will be executed once the document is fully loaded. This way the code can be placed (or remotely required) from the document head (but why would you want that?). Here's how it's done:

window.addEventListener('load', function () {
    // ... the code goes here
});

A (non-recommended) alternative is:

window.onload = function () {
    // ... the code goes here
};

Or (please avoid this, it's just an example) in HTML:

<body onload="someFunction();">

So, the resulting code might look like:

<!DOCTYPE html>
<html>
<head>
    <style>
        /* ... the CSS goes here */
    </style>
</head>
<body>
    <div id="box">I'm a box.</div>
    <script>
        // ... the JavaScript code goes here
    </script>
</body>
</html>

Special note regarding Internet Explorer

There's no support for addEventListener in Internet Explorer below version 9. You should use attachEvent instead.

like image 115
Oleg Avatar answered Sep 02 '25 17:09

Oleg


<script>
 var topPos = 0;
 var leftPos = 0;
 var leftAdder = 1;
 var topAdder = 1;
 var id;

    function move() {  
        clearInterval(id);
        id = setInterval(frame, 3);

        function frame() {

        leftPos = leftPos + leftAdder;
        topPos = topPos + topAdder; 
        document.getElementById("box").style.left = leftPos + 'px'; 
        document.getElementById("box").style.top = topPos + 'px'; 

        if (leftPos == 500) {
            leftAdder = -1;  
        }
        if (topPos == 350) {
            topAdder = -1;  
        }
        if (leftPos == 0) {
            leftAdder = 1;  
        }
        if (topPos == 0) {
            topAdder = 1;  
        }  
        }
    }

    function stop(){
        clearInterval(id);
    }

</script>
like image 28
indranatha madugalle Avatar answered Sep 02 '25 16:09

indranatha madugalle