Random Twitter Bootstrap Jumbotron Image on Each Page Load Using jQuery

Wednesday, June 11, 2014

The Twitter Bootstrap front-end framework provides a UI element called a Jumbotron. As stated at getbootstrap.com, it is “a lightweight, flexible component that can optionally extend the entire viewport to showcase key content on your site”.

In my particular case, I wanted to use the Jumbotron to display different, severely cropped photographs on each page load. This post will go through how to implement this using jQuery.

The Image Directory

Find the images you want to display and create a directory somewhere within your web directory. For this post I will be creating directory /images/jumbotron/ to store all of the images.

Be sure to name the images 01.jpg, 02.jpg, 03.jpg, 04.jpg, 05.jpg, etc.

The jQuery Code

Since you are already using the Twitter Bootstrap front-end framework, the jQuery library should already be loaded.

Next, you need the jQuery code to generate a random number on page load to complete the relative path for the background-image CSS attribute.

Put the following jQuery code within the head tags of your website:

<script type="text/javascript">

    $(document).ready(function() {
        var images = ['01.jpg', '02.jpg', '03.jpg', '04.jpg', '05.jpg'];

        $('.jumbotron').css({'background-image': 'url(/images/jumbotron/' + images[Math.floor(Math.random() * images.length)] + ')'});


The CSS Styling

Since you are already using the Twitter Bootstrap front-end framework, the Twitter Bootstrap CSS should also already be loaded.

There are some additional CSS attributes needed to set the height of the Jumbotron, to ensure the image spans the entire area of the Jumbrotron, and the image does not repeat itself.

Put the following CSS styling within the head tags of your website:

<style type="text/css">

        background-size: cover;
        background-repeat: no-repeat;
        height: 300px;


Notice that the background-image CSS attribute is not present. It is important that it is not in the CSS because if it is two images will be downloaded but only one displayed (the one set by the jQuery code). This is obviously inefficient. The only downside to also not having the background-image CSS attribute in the CSS is no image will be displayed within the Jumbotron if the user has Javascript disabled.

The HTML Markup

The last piece is the HTML markup.

Put the following HTML markup within the body tags where you want the Jumbotron to appear:

<div class="jumbotron">

Now, with each page load, a random image will be displayed within the Jumbotron.


Random background images CSS3

comments powered by Disqus