Clare12345
Clare12345

Reputation: 191

How do I have a different image load on each page refresh?

I am trying to have a different image load with each page refresh. I have tried this code:

<!DOCTYPE html><html><body> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script><script type="text/javascript" src="jquery-source"></script> <script>$(document).load( ... )</script><script type="text/javascript">(function($){

$.randomImage = {
    defaults: {

        //you can change these defaults to your own preferences.
        path: 'http://mysite.com/images/', //change this to the path of your images
        myImages: ['Testimonial1.png', 'Testimonial2.png', 'Testimonial3.png', 'Testimonial4.png', 'Testimonial5.png' ] //put image names in this bracket. ex: 'harold.jpg', 'maude.jpg', 'etc'

    }           
}

$.fn.extend({
        randomImage:function(config) {

            var config = $.extend({}, $.randomImage.defaults, config); 

             return this.each(function() {

                    var imageNames = config.myImages;

                    //get size of array, randomize a number from this
                    // use this number as the array index

                    var imageNamesSize = imageNames.length;

                    var lotteryNumber = Math.floor(Math.random()*imageNamesSize);

                    var winnerImage = imageNames[lotteryNumber];

                    var fullPath = config.path + winnerImage;


                    //put this image into DOM at class of randomImage
                    // alt tag will be image filename.
                    $(this).attr( {
                                    src: fullPath,
                                    alt: winnerImage
                                });

            }); 
        }   
});

}(jQuery));</script>
</body>
</html>

But I am a jQuery and JavaScript newb, and it's not working for me. I'm definitely doing something wrong, but I don't know where to begin with jQuery. I'm pretty sure it's a syntax error. Could anyone help me out?

Thank you!!

Upvotes: 0

Views: 6338

Answers (1)

Ast Derek
Ast Derek

Reputation: 2729

Some back and forth, but here is the code, this should work with no problems:

https://gist.github.com/AstDerek/5841966


Original answer

Your code works http://jsfiddle.net/AstDerek/AC6tu/

If you still have problems, try checking jQuery is loaded. The browser may complain if the call to the anonymous function is made outside of the first match of parenthesis:

Wrong:

})(jQuery);

Right:

}(jQuery));

Upvotes: 1

Related Questions