php - Loop random background image -
i want show random background image, starts loop of random other background images after 5 seconds.
first create array background-images:
<?php $bg = array('bg1.jpg', 'bg2.jpg', 'bg3.jpg', 'bg4.jpg', 'bg5.jpg', 'bg6.jpg', 'bg7.jpg', 'bg8.jpg', 'bg9.jpg', 'bg10.jpg', 'bg11.jpg'); $i = rand(0, count($bg)-1); $selectedbg = "$bg[$i]"; ?>
second append random image body:
<style> @media screen , (min-width: 600px) { body { background-image: url(<?php bloginfo('template_url'); ?>/images/backgrounds/<?php echo $selectedbg; ?>); } } </style>
now use php
or jquery
select random image , change background. how can achieve this?
if want loop background image every 5 seconds (without having user reloading page), can't on php, must done client side (javascript).
php tool generate html code rendered on user's browser, can't change page afterward, javascript made for.
<script type="text/javascript"> // declare list of backgrounds var images = ['bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg']; // declare function changes background function setrandombackground() { // choose random background var randombackground = images[math.floor(math.random() * images.length)]; // set background jquery $('body').css('background-image', 'url("images/' + randombackground + '")'); } // declare function sets initial background, , starts loop. function startloop() { // set initial background. setrandombackground(); // tell browser execute setrandombackground every 5 seconds. setinterval(setrandombackground, 5 * 1000); } // 1 page has finished loading, execute startloop function $(document).ready(startloop); </script>
Comments
Post a Comment