Choosing random image using jquery

You must include jquery js in your code. Now define a header css class in <head>


<style type="text/css">
          #header {height: 250px};
 </style>

Now define a div inside your <body> tag where jquery append randomly images..
<div id="banner"> </div>

Now put this code at the bottom of your code before </html> tag...

<script type="text/javascript">
    var images = ['img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg'];

    $(document).ready(function() {
          
            $('#header').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});
        
          $('<img src="images/' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#banner');
 
  });

</script>

Here we have placed these images(img1,img2,img3,img4 and img5.jpg)  inside images directory.

Comments

Popular posts from this blog

Struts 2 : Warning :No configuration found for the specified action: 'Login.action' in namespace: '/'

Upload csv file at Google Cloud Storage using java

Read Images from a xlsx file using Apache POI