Daniel Ramirez-Escudero
Daniel Ramirez-Escudero

Reputation: 4047

onload javascript assign background image to div

I have this code which loads different images to an "img" by printing its url via javascript in its "src". After the CSS does the magic regarding the content in the "img" tag.

$(window).load(function() {
    var randomImages = ['img1','img2','img3','img4','img5','img6','img7','img8','img9','img10','img11','img12','img13','img14','img15','img16','img17','img18','img19','img20','img21','img22','img23','img24','img25','img26','img27','img28','img29','img30'];
    var rndNum = Math.floor(Math.random() * randomImages.length);

     var $win = $(this);
     var iMac = $(window).width() > 1920 ? '_imac' : '';
     var $img = $('#background').attr('src', '_img/bg/index_rnd/' + randomImages[rndNum] + iMac + '.jpg').css({'position':'fixed','top':0,'left':0});
        function resize() {
            if (($win.width() / $win.height()) < ($img.width() / $img.height())) {
              $img.css({'height':'100%','width':'auto'});
            } else {
              $img.css({'width':'100%','height':'auto'});
            }
        }
        $win.resize(function() { resize(); }).trigger('resize');
    });

I'm creating a new web and I would like to use the same system selecting a picture of an array, BUT applying the url of the foto to a css background image.

#home{
    background: url(INSERT URL OF JAVASCRIPT HERE) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    }

I tried in the code below, but I think in a clumsy way. I don;t know if this is even possible or if there is a more simple way than this method via javascript. As you see I'm not an expert.

$(window).load(function() {
    var randomImages = ['img1','img2','img3'];
    var rndNum = Math.floor(Math.random() * randomImages.length);
    var url = 'url(_img/bg_array/' + randomImages[rndNum] + '.jpg)'


    $('#home').css({
        'background:' url 'no-repeat' 'center' 'center' 'fixed', 
        '-webkit-background-size': 'cover',
        '-moz-background-size': 'cover',
        '-o-background-size': 'cover',
        'background-size': 'cover'
        });
    }

THANK YOU!!!!

EDIT: MORE INFO //////////////////////////////

The answer of jfriend00 seems 100% correct and logic. I'm trying to use the second option. I've tried both options and neither seems to work. I've also tried to apply a simple code to #home via javascript and it doesnt work... So I think there is a problem with the link between the javascript file and the html, maybe the problem is somewhere else...

Here I will put more possible useful information. I insert my html and my connections to differnt files in the head, maybe thats helpful. I'm creating a web with a horizontal layout. It works perfectly via jquery...

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>DJ Femke</title>

        <!-- JAVASCRIPT CONNECTIONS -->

        <script type="text/javascript" src="_js/jquery-1.3.1.min.js"></script>
        <script type="text/javascript" src="_js/jquery.scrollTo.js"></script>
        <script type="text/javascript" src="_js/scroll_resize.js"></script>
        <script type="text/javascript" src="_js/onload.js"></script>


        <!-- CSS CONNECTIONS -->
        <link type="text/css" rel="stylesheet" href="_css/style.css" media="screen"/>
    </head>
    <body>
        <div id="wrapper">
            <div id="mask">

                <div id="booking" class="item">

                    <a name="item1"></a>
                    <div class="content">item1 
                        <a href="#booking" class="panel">1</a> | 
                        <a href="#about_me" class="panel">2</a> | 
                        <a href="#home" class="panel">3</a> | 
                        <a href="#music" class="panel">4</a> | 
                        <a href="#photo_video" class="panel">5</a>
                        <a href="#contact" class="panel">6</a>
                        <p>BOOKING</p>
                    </div>
                </div>

                <div id="about_me" class="item">
                    <a name="item2"></a>
                    <div class="content">about_me
                        <a href="#booking" class="panel">1</a> | 
                        <a href="#about_me" class="panel">2</a> | 
                        <a href="#home" class="panel">3</a> | 
                        <a href="#music" class="panel">4</a> | 
                        <a href="#photo_video" class="panel">5</a>
                        <a href="#contact" class="panel">6</a>
                        <p>ABOUT ME</p>
                    </div>
                </div>

                <div id="home" class="item" src="">
                    <a name="item3"></a>
                    <div class="content">item3
                        <a href="#booking" class="panel">1</a> | 
                        <a href="#about_me" class="panel">2</a> | 
                        <a href="#home" class="panel">3</a> | 
                        <a href="#music" class="panel">4</a> | 
                        <a href="#photo_video" class="panel">5</a>
                        <a href="#contact" class="panel">6</a>
                        <p>HOME</p>
                    </div>
                </div>

                <div id="music" class="item">
                    <a name="item4"></a>
                    <div class="content">item4
                        <a href="#booking" class="panel">1</a> | 
                        <a href="#about_me" class="panel">2</a> | 
                        <a href="#home" class="panel">3</a> | 
                        <a href="#music" class="panel">4</a> | 
                        <a href="#photo_video" class="panel">5</a>
                        <a href="#contact" class="panel">6</a>
                        <p>MUSIC</p>
                    </div>
                </div>

                <div id="photo_video" class="item">
                    <a name="item5"></a>
                    <div class="content">item5
                        <a href="#booking" class="panel">1</a> | 
                        <a href="#about_me" class="panel">2</a> | 
                        <a href="#home" class="panel">3</a> | 
                        <a href="#music" class="panel">4</a> | 
                        <a href="#photo_video" class="panel">5</a>
                        <a href="#contact" class="panel">6</a>
                        <p>PHOTO AND VIDEO</p>
                    </div>
                </div>

                <div id="contact" class="item">
                    <a name="item6"></a>
                    <div class="content">item6
                        <a href="#booking" class="panel">1</a> | 
                        <a href="#about_me" class="panel">2</a> | 
                        <a href="#home" class="panel">3</a> | 
                        <a href="#music" class="panel">4</a> | 
                        <a href="#photo_video" class="panel">5</a>
                        <a href="#contact" class="panel">6</a>
                        <p>CONTACT</p>
                    </div>
                </div>

            </div>
        </div>  
    </body>
</html>

The javascript in my file onload.js is the following:

$(window).load(function() {
    var randomImages = ['img1','img2','img3'];
    var rndNum = Math.floor(Math.random() * randomImages.length);
    var url = 'url(_img/bg_array/' + randomImages[rndNum] + '.jpg)'

    $('#home').css({
        'background': url + 'no-repeat center center fixed', 
        '-webkit-background-size': 'cover',
        '-moz-background-size': 'cover',
        '-o-background-size': 'cover',
        'background-size': 'cover'
    });
}

Maybe its handy... my file structure: enter image description here

Upvotes: 0

Views: 5716

Answers (2)

jfriend00
jfriend00

Reputation: 707238

You have two choices for setting the background image via javascript. You can set just the background-image CSS property or you can add strings together to form the entire string for the background property.

Option 1:

$(window).load(function() {
    var randomImages = ['img1','img2','img3'];
    var rndNum = Math.floor(Math.random() * randomImages.length);
    var url = 'url(_img/bg_array/' + randomImages[rndNum] + '.jpg)';


    $('#home').css('background-image', url);
});

Option 2:

$(window).load(function() {
    var randomImages = ['img1','img2','img3'];
    var rndNum = Math.floor(Math.random() * randomImages.length);
    var url = 'url(_img/bg_array/' + randomImages[rndNum] + '.jpg)'

    $('#home').css({
        'background': url + ' no-repeat center center fixed', 
        '-webkit-background-size': 'cover',
        '-moz-background-size': 'cover',
        '-o-background-size': 'cover',
        'background-size': 'cover'
    });
 });

You were also missing a closing ); at the end of your code that completes the $(window).load() statement.

Working example of the 2nd option: http://jsfiddle.net/jfriend00/rGkww/

Upvotes: 2

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

Edit: Oh yea, the other poster was right. I didn't check the random number generation... but the rest still holds true.

I don't use jquery...

but in regular Javsacript it would be more like: ** Warning, untested code **

var imgs = ["foo1.jpg", "foo2.jpg"];
var idx = Math.floor(Math.random() * imgs.length)
var img = imgs[idx];

var el = document.getElementById('home');
el.style.backgroundImage="url('" + img + "')";

Upvotes: 0

Related Questions