How to make elements random appear within the browser window on refresh using javascript?

I’m making my homepage, and I need some help with the javascript. I want the elements I made to random appear within the browser window every time you refresh the page. This is my homepage so far: http://folk.ntnu.no/manordt/wu1/Heimeside/framside.html

The code I’m using now is this:

$('.element').each(function(i,el){

var tLeft = Math.floor(Math.random()*1000),

tTop = Math.floor(Math.random()*500);

$(el).css({position:'absolute', left: tLeft, top: tTop});

});

And I’m using the jquery file: jquery-3.3.1.min.js

My problem is that now the elements appear within the size 500 x 1000, but I want it to random appear within the browser window (so if your window is 400 x 500, it will not go beyond the window).

I’m new to javascript, but really want this to work!

Thank you <3

Well, if you want random elements, you’ll have to find a way to randomly select some of the elements, not each element. Give it a try yourself, and we’ll help you refine it.

Some hints:
a jquery selector ($(".element")) returns an array-like structure with numerical indexes.
You’ve already used Math.random() and Math.floor() before.
Because you’re doing it randomly, you don’t care if the same number comes up more than once.

Javascript exposes this as window.innerWidth and window.innerHeight , respectively. Keep in mind that this is the total width/height, and your left/top positioning does not account for the width/height of the element.

Thank you so much!

It worked replacing 1000 and 500 with window.innerWidth and window.innerHeight. Now it is like you said, the elements go a little outside the window, do you know how I can make them not do this?

My JS is very basic but as a start I would assume that you need to find height and width of each image and if that dimension combined with the random position is greater than the available width/height then make the random position the viewport width minus the image width (and same for the height).

You would also need to wait for the images to load fully before getting their dimensions. As I said my jS is basic but this seems to work.

$(window).on("load", function() {
    //Dra element

    var container = document.querySelector("#containerElement");
    var activeItem = null;

    var active = false;

    container.addEventListener("touchstart", dragStart, false);
    container.addEventListener("touchend", dragEnd, false);
    container.addEventListener("touchmove", drag, false);

    container.addEventListener("mousedown", dragStart, false);
    container.addEventListener("mouseup", dragEnd, false);
    container.addEventListener("mousemove", drag, false);

    function dragStart(e) {

        if (e.target !== e.currentTarget) {
            active = true;

            // this is the item we are interacting with
            activeItem = e.target;

            if (activeItem !== null) {
                if (!activeItem.xOffset) {
                    activeItem.xOffset = 0;
                }

                if (!activeItem.yOffset) {
                    activeItem.yOffset = 0;
                }

                if (e.type === "touchstart") {
                    activeItem.initialX = e.touches[0].clientX - activeItem.xOffset;
                    activeItem.initialY = e.touches[0].clientY - activeItem.yOffset;
                } else {
                    console.log("doing something!");
                    activeItem.initialX = e.clientX - activeItem.xOffset;
                    activeItem.initialY = e.clientY - activeItem.yOffset;
                }
            }
        }
    }

    function dragEnd(e) {
        if (activeItem !== null) {
            activeItem.initialX = activeItem.currentX;
            activeItem.initialY = activeItem.currentY;
        }

        active = false;
        activeItem = null;
    }

    function drag(e) {
        if (active) {
            if (e.type === "touchmove") {
                e.preventDefault();

                activeItem.currentX = e.touches[0].clientX - activeItem.initialX;
                activeItem.currentY = e.touches[0].clientY - activeItem.initialY;
            } else {
                activeItem.currentX = e.clientX - activeItem.initialX;
                activeItem.currentY = e.clientY - activeItem.initialY;
            }

            activeItem.xOffset = activeItem.currentX;
            activeItem.yOffset = activeItem.currentY;

            setTranslate(activeItem.currentX, activeItem.currentY, activeItem);
        }
    }

    function setTranslate(xPos, yPos, el) {
        el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
    }


    //Random plassering innanfor vindauge

    $('.element').each(function(i, el) {

        var availWidth = window.innerWidth,
            availHeight = window.innerHeight,
            tLeft = Math.floor(Math.random() * availWidth),
            tTop = Math.floor(Math.random() * availHeight),
            elWidth = $(this).width(),
            elHeight = $(this).height();

        console.log('width = :' + elWidth);
        console.log('height = :' + elHeight);

        if (tLeft + elWidth > availWidth) {
            tLeft = tLeft - elWidth;
        }
        if (tTop + elHeight > availHeight) {
            tTop = tTop - elHeight;
        }
        $(el).css({
            position: 'absolute',
            left: tLeft,
            top: tTop
        });

    });

});

I’m sure that can be simplified by one of the experts here but may help as a starting point :slight_smile:

Essentially, yes. At this point it’s not so much a Javascript problem, as it is a basic mathematical problem of Cartesian coordinates and fitting an object to a plane.

As i said before,marianordtvelt, this is the total height. Defining a position for an element defines the top left corner of that element. In order to randomly assign a place for each element that will fit inside the window, instead of your limits being 0 and the window’s height, it would be 0 and the window’s height minus the element’s height.

Consider it this way. We’ll put some actual numbers to it so its a little less theoretical. Lets say you’ve got a window that is 400x500, and an image that is 75x50.

In order to make sure that my element fits on the screen vertically, I know that I cannot start the image anywhere after 450, because the image is 50 pixels high. So i can generate a random number between 0 and 450, and know for sure my image wont go off the bottom of the screen.
I know I cannot start the image anywhere after 325 in from the left, because the image is 75 pixels wide and my window is only 400 pixels wide. So I can generate a random number between 0 and 325.

omg you’re a real life saver, thank you so much! Figured it out eventually thanks to you, forever grateful <3 <3 Now it works like a charm!

Thank you so much for looking at it :slight_smile: I couldn’t make it work, but I figured out another way! Thanks anyway!

This is how it looks like now, and it’s working:

$(‘.element’).each(function(i,el){

var tLeft = Math.floor(Math.random()*(window.innerWidth-363)+0),
    tTop  = Math.floor(Math.random()*(window.innerHeight-200)+50);

$(el).css({position:'absolute', left: tLeft, top: tTop});

});

It was a fully working example that I posted :slight_smile: You must have missed something along the way. :wink:

That would assume that all your images are the same size or smaller. The example I posted (which I have working perfectly locally) takes into account the size of each actual image.

I didn’t see that you had updated your page yet so can’t confirm if its working for you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.