Use JavaScript to load and set a background image for a div

When it comes to loading different images onto an "img" tag by printing their URLs using JavaScript and then letting CSS manipulate the content in the tag, I have a code snippet that does just that.

$(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 am currently working on a new website project and would like to implement a similar system where I select an image from an array and apply its URL as a background image via CSS for the #home element.

#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 attempted to achieve this functionality but feel like my approach is not optimal. I'm not entirely sure if what I want to do is even possible without using JavaScript or if there's a simpler way that I may be overlooking due to lack of expertise.

$(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 for any help!

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

Answer №1

When it comes to setting the background image using JavaScript, you have a couple of options. You can either set the background-image CSS property on its own, or you can concatenate strings to create the complete string for the background property.

Here's 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);
});

And here is 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'
    });
 });

Don't forget to add a closing ); at the end of your code to complete the $(window).load() statement.

For a working example of the second option, check out this link: http://jsfiddle.net/jfriend00/rGkww/

Answer №2

Update: I completely overlooked the random number generation aspect mentioned by another user...however, my main point still stands.

I stay away from using jquery...

In plain JavaScript, the code would look something like this: ** Proceed with caution, code has not been tested **

var images = ["image1.jpg", "image2.jpg"];
var index = Math.floor(Math.random() * images.length);
var selectedImage = images[index];

var element = document.getElementById('homepage');
element.style.backgroundImage = "url('" + selectedImage + "')";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Priority is given to strings over numbers

Here's some code I'm working with: <tbody> <tr> <td class="float-left"> <!-- {{selectedTemplat?.modifiedAt | da ...

Utilizing JQuery Mobile to handle multiple forms on a single page and submitting each form uniquely by its ID using JQuery Post

After experimenting with assigning the same form ID to all forms on the page and also giving each form individual IDs with unique.submit functions, I encountered an issue where only the first form would work while the rest would redirect me back to the hom ...

Manipulating web elements by traversing through selected identifiers in LocalStorage and eliminating them from the document layout

I have a multitude of localStorage keys, including ones labeled Cart, Viewed, and Trash. There are two aspects to my query: 1) What is the most efficient way to loop through the item IDs in localStorage and add a class or data attribute to the correspond ...

The Angular.js UIBootstarp Timepicker is displaying the "ng-invalid" class when used with an input type of "number"

Currently, I am working on incorporating a time picker using UIBootstrap and angular.js. By default, the timepicker utilizes {{input type="text}} for capturing hours and minutes. However, since I intend to use this feature on mobile devices, I need to di ...

Load the dropdown menu with JSON data but encounter an error: SyntaxError caused by an unexpected token `{` in

I am currently working on populating a dropdown menu with the values of the 'styleName' field from a JSON data file. Here is an example of my JSON data: {"name":{"styleName":"name","fillType":"none","fillTrans":"0","outlineType":"solid","outlin ...

What is the best way to convert minutes into both hours and seconds using javascript?

In order to achieve this functionality, I am trying to implement a pop-up text box where the user can choose either h for hours or s for seconds. Once they make their selection, another pop-up will display the answer. However, I am facing issues with gett ...

Troubleshooting Problems with Ruby Arrays, JavaScript, and JSON

I am facing a challenge with rendering a highcharts plugin in my rails application. I suspect it could be related to the sql queries fetching data from the database and converting them into a ruby array that the javascript code fails to interpret correctly ...

Display JavaScript and CSS code within an Angular application

I am working on an Angular 1.x application (using ES5) where I need to display formatted CSS and JS code for the user to copy and paste into their own HTML file. The code should include proper indentations, line-breaks, etc. Here is a sample of the code: ...

Error message: "When using Webpack 4 with Bootstrap, a TypeError occurs where property 'jquery' is read as undefined."

I've recently delved into the world of webpack and everything seems to be running smoothly. However, when I run my webpack app, I encounter the following error within Bootstrap: var version = $.fn.jquery.split(' ')[0].split('.'); ...

Arranging React Grid Items with Stylish Overlapping Layout

Is there a way to create a react-grid-layout with 100 grid points width, while ensuring that the grid items do not overlap? https://i.sstatic.net/CQiVh.png (Reducing the number of columns can prevent overlap, but sacrifices the 100-point width resolution ...

Is there a way to locate a child div using the mouse within a parent div that only has a class name assigned to it?

Hey there, I've been searching for a solution to my issue but haven't found exactly what I need. I'm new to jquery and currently working on creating a newspaper layout form. Adding new divs within the layout canvas is easy with this code: ...

Utilizing Multiple Checkboxes for Precision Search Refinement

Big thanks to Khalid Ali for the support provided up until now. I am currently working with an array of songs that each have descriptions, keywords, etc. I have a set of checkboxes that I want to use to refine a search. Essentially, if someone selects the ...

Tips for Saving JSON Response from Fetch API into a JavaScript Object

I am facing an issue trying to store a Fetch API JSON as a JavaScript object in order to use it elsewhere. The console.log test is successful, however I am unable to access the data. The Following Works: It displays console entries with three to-do items: ...

Incorporate a minimum height requirement for enabling the scroll to top feature

I am currently dealing with some JavaScript code that scrolls to a specific div when clicked. However, I have encountered an issue where the div is displayed at the very top of the page, causing it to go behind a fixed header that is 90px in height. As a r ...

Tips for creating sliding header content alongside the header

Is it possible for the content in the header to scroll up, displaying only the navigation list and hiding the logo when a user scrolls on the website? Currently, while the header background slides up, the content within the header remains in place. I feel ...

Generate a unique identifier for the HTML content

Is there a more efficient way to assign unique id tags to certain words using vanilla javascript? For example: <p>All the king's horses ran away.</p> For instance, "All" would have the id "term1", "King's" would have "term2", and ...

Is it recommended to rely on Javascript for altering the content of a div across an entire website?

I am in the process of creating my personal portfolio and have a few inquiries regarding the framework to implement. Currently, I have an index.html page that contains all the information I want displayed when visitors land on the site. Additionally, ther ...

Using jQuery to communicate with a WCF service via Ajax results in receiving a bad

I'm struggling to set up an auto-complete feature, where I can successfully retrieve JSON data using Fiddler. However, when I try to implement it in my code, I keep encountering a connection error. Here is the code snippet: <htm> <Head> & ...

ReactStrap: Transparency issue with DropDown items on mobile devices

I've encountered an issue with my dropdown menu that works perfectly on desktop: https://i.sstatic.net/73Z0X.png However, on mobile devices, it appears to be transparent for some reason: https://i.sstatic.net/dhtOw.png Here is the code snippet ...

Creating a capsule-shaped button using HTML and CSS:

I'm trying to create a button that mimics the design in the code snippet. Is this method the most effective way, or is there a simpler approach I should consider? It seems like a lot of work just to achieve rounded corners. #p1,#p2{ height:25px; ...