AndrewLeonardi AndrewLeonardi - 3 months ago 9
HTML Question

How to set custom window height?

Working on a project where objects move around the screen randomly. I'm trying to have a element at the top that does not get covered by these objects. This is my current code:

function makeNewPosition(){

// Get viewport dimensions
var h = $(window).height() - 150;
var w = $(window).width() - 100;

var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);

return [nh,nw];

}


This works well but I'm needing to block off, lets say 150px at the top of the screen where the objects cannot go. For some reason I have been unable to do this. How would I modify my code to accomplish this?

Thanks for any help!

Answer

You need to set the 150px as offset from top. Otherwise the bottom 150px of your screen will be untouched by the objects, not the top.

function makeNewPosition() {
    var h = $(window).height() - 150;
    var w = $(window).width() - 100;

    var nh = Math.floor(Math.random() * h) + 150;
    var nw = Math.floor(Math.random() * w);

    return [nh,nw];    
}

If you want to let the left and right area of 100px to be untouched too, you need to substract 200px and add 100px to the result.

function makeNewPosition() {
    var h = $(window).height() - 150;
    var w = $(window).width() - 200;

    var nh = Math.floor(Math.random() * h) + 150;
    var nw = Math.floor(Math.random() * w) + 100;

    return [nh,nw];    
}