Search code examples
javascriptresolution

window.innerWidth in JavaScript


here's my code:

<body>
    <header></header>
    <div id="slider" class="slider">
        <p>Slider content</p>
    </div>
    <script src="jas.js"></script>
</body>


var divPos = 50;
var direction = "L";

function preparepage() {
    document.getElementById("slider").style.position = "absolute";
    document.getElementById("slider").style.left = divPos + "px";
    document.getElementById("slider").style.top = "50px";
    animateDiv = setInterval(beginAnimate,50);
}

function beginAnimate () {
    if (direction == "L") {
        divPos+=50;
        if (divPos == 1300) {
            direction = "R";
        }
    } else if (direction == "R"){
        divPos-=50;
        if (divPos == 150) {
            direction = "L";
        }
    }
    document.getElementById("slider").style.left = divPos + "px";
}

window.onload = function () {
    setTimeout(preparepage,200);
};

I want #slider to go from left to right and when it reaches certain point to go back. My code works fine, but I tried it this way:

if (direction == "L") {
    divPos+=50;
    if (divPos == window.innerWidth - 300) {
        direction = "R";
    }
}

and it goes left for ever. Why is that happening? What can I do to make it go back at certain point, no what what screen resolution is?


Solution

  • Use:

    if (divPos > window.innerWidth - 300) {
    

    Unless the window's width is a multiple of 50, incrementing divPos by 50 won't hit innerWidth - 300 exactly, so you need to be less exacting.