b-withers / image-randomizer

This small repo picks a random image and displays it on each page refresh.

Home Page:https://b-withers.github.io/image-randomizer/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Random Hero Image on refresh

On a website I was developing, I wanted to have a random "Hero" image displayed each time the page was refreshed. What I thought would be a simple solution turned out to be a little more involved than I thought. Here is my solution!


  • HTML
  • CSS
  • jQuery
  • Bootstrap

I put the function inside the HTML, but it could easily be moved to a external file. An array of images is created, and then called randomly and displayed to the specified class, easy peasy

    <script type="text/javascript">
        $(function() {
            //array of images, I named them in numerical order for simplicty
            var images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg'];
            //jQuery function contains path to images, and function to call a random image.
            $('.hero').css({'background-image': 'url(img/backgrounds/' + images[Math.floor(Math.random() * images.length)] + ')'});
            });
    </script>

About

This small repo picks a random image and displays it on each page refresh.

https://b-withers.github.io/image-randomizer/


Languages

Language:HTML 78.6%Language:CSS 21.4%