Jeeva Jeeva - 2 months ago 10
jQuery Question

I want to load the background first using jquery but my code doesn't seem to work

Below is the code. but i don't know what the problem is. I have a array of background images after each load it keeps changing[This is my intention]. Now i planned to use javascript to load the background first but my code doesn't work though it works with regular style tags. I don't know what am doing wrong here. below are the code.

This below code works but takes time to load the image

<?php
$bg = array('login_bg.jpg', 'login_bg2.jpg', 'login_bg3.jpg', 'login_bg4.jpg', 'login_bg5.jpg', 'login_bg6.jpg', 'login_bg7.jpg', 'login_bg8.jpg', 'login_bg9.jpg' ); // array of filenames

$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = $bg[$i]; // set variable equal to which random filename was chosen
?>



<style>

body{
background-image:url("<?php echo $base_url; ?>assets/images/<?php echo $selectedBg; ?>");
}

</style>


This code doesn't work. I'm doing this because i want to load the BG first.

<?php
$bg = array('login_bg.jpg', 'login_bg2.jpg', 'login_bg3.jpg', 'login_bg4.jpg', 'login_bg5.jpg', 'login_bg6.jpg', 'login_bg7.jpg', 'login_bg8.jpg', 'login_bg9.jpg' ); // array of filenames

$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>

<script>
var img1 = new Image();

img1.src="<?php echo $base_url; ?>assets/images/<?php echo $selectedBg; ?>";


$('body').css('background-image', 'url('+ img1.src + ')');

</script>

Answer

Is your path correct?

In my example, this would be this:

http://localhost/test/assets/images/login_bg.jpg

called from this file:

http://localhost/test/index.php

EDIT:

Your JS/jQuery is faster than your site. Try to use $( document ).ready(function() {

$( document ).ready(function() {
    $('body').css('background-image', 'url('+ img1.src + ')');
});