Chrish
Chrish

Reputation: 1067

Why is my js only working correctly when the page is refreshed?

No idea why this is happening and Google is only bringing up things to do with AJAX. The script randomly places images within the window boundary. When I load the page the images are placed randomly but aren't within the window boundary, when I refresh the page they are... anyone have any ideas?

Here's the code I have:

$(document).ready(function() {
    // Randomly place CMYK images on contact page
        function randomFromTo(from, to){
            return Math.floor(Math.random() * (to - from + 1) + from);
        }

        function moveRandom(obj) {
            // Get window data
                var wPos = $('body').offset();
                var wWidth = $('body').width();
                var wHeight = $('body').height();

            // Get moveable element size
                var eWidth = obj.width();
                var eHeight = obj.height();

            // Maximum and minimum positions
                var maxX = wPos.left + wWidth - eWidth;
                var maxY = wPos.top + wHeight - eHeight;
                var minX = wPos.left;
                var minY = wPos.top;

            // Set new position
                var newX = randomFromTo(minX, maxX);
                var newY = randomFromTo(minY, maxY);

                obj.css({
                    'position' : 'absolute',
                    'z-index' : '0',
                    'left' : newX,
                    'top' : newY
                });
        }

        $('.selfie img').each(function() {
            moveRandom($(this));
        });
});

Upvotes: 0

Views: 65

Answers (1)

nanobar
nanobar

Reputation: 66355

My guess is that you are checking the image width and height on document ready, which does not guarantee the images have loaded. After the first load they are cached so you are just fortunate they are ready.

Try changing $(document).ready to $(window).load which ensures the images are loaded.

Upvotes: 4

Related Questions