Setting a div's background using JavaScript works flawlessly on jsfiddle.net, but encounters issues when implemented in actual code

contains the files you need. For reference, here is the link to the code on

I have attempted to remove all unnecessary elements from the actual project, but it has not made a difference.

document.getElementById("image").style.backgroundImage = "url(" + dir + images[randomCount] + ".jpg" +  ")"; 

Answer №1

To ensure your code runs properly, make sure it is executed after the DOM has loaded. You can achieve this by either moving the code below the </body> tag or using the window.onload handler.

It's important to remember that assignment statements should end with a ;, not a ,.

window.onload = function() {
    var dir = 'http://seriousphotography.co.uk/HD-Site/images/album/01/';
    var images = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10"];
    var randomCount = Math.floor(Math.random() * images.length);
    document.getElementById("image").style.backgroundImage = "url(" + dir + images[randomCount] + ".jpg" +  ")"; 
};

For a more concise version:

window.onload = function() {
    var dir = 'http://seriousphotography.co.uk/HD-Site/images/album/01/';
    var images = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10"];
    var randomCount = Math.floor(Math.random() * images.length);
    document.getElementById("image").style.backgroundImage = "url(" + dir + images[randomCount] + ".jpg" +  ")"; 
};

Check out Get random item from JavaScript array for reference.

Using classes and jQuery, you can simplify it further:

$("#image").addClass("image"+images[randomCount]);

Fiddle: http://jsfiddle.net/barmar/LgjzvcpL/12/

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

Define the post route methods effectively

I encountered a routing error while working on an application using express.js with node. Despite my best efforts, I am unable to handle post requests properly and consistently receive an HTTP 500 error. Below is the code snippet from my server.js file: v ...

update the componentWillMount() function

I am currently exploring the code found at https://github.com/Spyna/react-store/blob/master/src/createStore.js What adjustments do I need to make in order to align with the deprecated componentWillMount lifecycle method? CreateStore const createStore = ...

Sort array of objects alphabetically and move objects with value to the beginning

I have a dataset that consists of different arrays of objects. When I log myData, the output looks something like this: [ { name: 'Cdb', image: 'xxx', coll: 'xxx' }, { name: 'Bcd', image: &a ...

How do I return a <div> element to its initial state after JavaScript has made changes to it?

So, I have this situation where a DIV contains a form. After users submit the form successfully, I want to replace the form with a simple message saying "everything is good now". This is how I currently do it: $("#some_div").html("Yeah all good mate!"); ...

Use the no-repeat feature to set the background image in an Asp:Chart

I have been working with the asp:Chart control and have found that its BackImage property functions well. However, I have encountered two issues while trying to set the background image. I am unable to successfully set the no-repeat property of the Bac ...

Align a header and a block of text in a vertical manner within a div

Struggling to align a h1 element and p vertically in the middle of a left-floated div, but they end up next to each other aligned vertically. Seems like table-cell display is the culprit, but not sure how to achieve vertical alignment without it. The curr ...

Sending a Single Input Field value to a Controller in Laravel using JQuery

Looking to submit a single form value using jQuery to a database in Laravel. Below is the input field: <input type="text" id="comment"> <button id="cmntSubmit" type="button">Post</button> Check out the jQuery code I am using: $(docum ...

Attempting to use Model.remove() is proving to be completely ineffective

Currently, I am utilizing expressjs (version 3.10.10), mongoose (version 3.10.10), and mLab for my project. Below is the code snippet: app.get("/deleteDevice/:query", function(req, res) { var query = req.params.query; query = JSON.stringify(quer ...

How can I create an HTML select dropdown menu with a maximum height of 100% and a dynamic size?

The dropdown menu I created using an HTML select tag contains a total of 152 options. However, the large number of options causes some of them to be out of view on most monitors when the size is set to 152. I attempted to limit the number of displayed opti ...

Using MySQL data in an EJS file to create a personalized Profile Page

In the midst of a personal project aimed at honing my web development skills and gaining a deeper understanding of the intricacies of the field, I have hit a roadblock. The focus of this project is to create a profile page, and while I have successfully co ...

Instructions on how to make a radio button selected when clicked are as follows:

My radio button is currently checked, but I would like it to be onclicked because there is a Javascript function that uses the on.click function. Are there any possible methods or examples to achieve this? <label style="margin-left:177px;">Order Ty ...

Javascript is coming back with a message of "Access-Control-Allow-Origin" not being allowed

I've been encountering some unusual challenges with my React application related to the Access-Control-Allow-Origin issue. Initially, I had similar issues with the login and registration system which I thought were resolved, but now I'm facing di ...

Applying CSS transitions and transforms to SVG elements

Having trouble animating an SVG group with CSS transitions after applying a CSS transform? Check out my code below and let me know if you spot the issue. Inline SVG Code <a href="javascript:void(0)" class="hub-icon-container"> <svg xmlns="ht ...

Steps to clear a form after submitting it

Hello all, I have a rather complex form that sends a message successfully with an alert after submission. I'm wondering how I can clear the entire form once it has been submitted to make it simple? Below is my HTML Form and JavaScript code. I would l ...

Center align text in the uib-progressbar

Is it possible to center align text in the uib-progressbar? I attempted using position:absolute, but I would like to display a list of progress bars in a UI grid that includes scrollable content. The goal is for the text to remain fixed while the progress ...

Showing options in the navigation bar upon user authentication with Passport in NodeJS

When a user is connected, I want the navbar to display "Profile of: {USER}", otherwise it should show a set of Sign up/Login tabs. The challenge lies in using EJS with separate "head.ejs" and "header.ejs" sections placed in a /partials folder within the / ...

The property 'scrollHeight' is undefined and cannot be read

I've created a messaging system using javascript and php, but I'm facing an issue. When new messages are received or the chat log grows longer, it creates a scrollbar. The problem is that when a new message arrives, the user has to manually scrol ...

The error message "Cannot read property 'option0' of undefined" occurs when using Node.js with Express and EJS

script.js var choices = { choice0: 11, choice1: 'choice1', choice2: 'choice2', choice3: 'choice3', choice4: 'choice4', choice5: 'choice5', choice6: 'choice6', choice7: 'choice7', choice ...

The absence of transpiled Typescript code "*.js" in imports

Here is an example of the code I am working with: User.ts ... import { UserFavoriteRoom } from "./UserFavoriteRoom.js"; import { Room } from "./Room.js"; import { Reservation } from "./Reservation.js"; import { Message } from ...

Conceal the Addon Tab across all pages in Storybook

Is there a way to globally hide an Addon Tab without disabling the addon itself? Specifically, I am using version 5.3.18 of Storybook with React and I want to hide the tab panel from the addon "styled-component theme". I apologize for the basic question, ...