Utilizing JavaScript and the Document Object Model (DOM) to display images within a

My main goal is to have images load dynamically as the background of the browser frame, without any white spaces or repeats. I've successfully achieved this statically, but now I want to implement it so that different images are generated randomly.

When I use

document.body.style.backgroundImage="url('img/" + image.image + "')";
, the image loads fine but sometimes there is white space near the bottom border. I tried setting it within a div using
document.getElementById("pic").style.backgroundImage = "url('img/" + image.image + "')";
or
document.getElementById("pic").style.background = "url('img/" + image.image + "')";
, but it only gives me a white background.

Interestingly, if I specify a static image in the CSS for my 'pic' class, it works perfectly. For example:

background: url("http://lorempixel.com/1600/1200/nature/") ;

Here's the CSS I'm using:

body {  
  top:0px;
  left:0px;
  height:100%;
  width:100%;  
  z-index:-1;
  opacity:1;
  background-repeat: no-repeat;
  background-size: cover;
}
.pic {
  position:fixed;
  top:0px;
  left:0px;
  width:100%;
  height:100%;
  z-index:-1;
  opacity:1;
  background-repeat: no-repeat;
  background-size: cover;
}

I am open to using either the body or the div element to achieve my goal. I just want to dynamically load images without any issues. If anyone can help explain what I'm doing wrong with loading the background of the div dynamically, I would greatly appreciate it.

Answer №1

It appears that you are assigning the class 'pic' to a div tag, but then attempting to retrieve the element with the id 'pic'.

To resolve this issue, you have two options:

Option 1:

<div id="pic">

Instead of:

<div class="pic">

Option 2:

document.getElementsByClassName("pic")[0].style.backgroundImage = "url('img/" + image.image + "')";

Instead of:

document.getElementById("pic").style.backgroundImage = "url('img/" + image.image + "')";

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

Looking for a vertical scrollbar solution for your idangerous vertical swiper?

Incorporating idangerous vertical swiper with two slides in a mobile app through jquery mobile has proven challenging. Specifically, I am struggling to implement a vertical scroll bar in the second slide due to its fixed height and the potential collision ...

Reduce the size of a webpage by 10%

Have you ever noticed that when you press Ctrl+- on any browser, the page scales down to 90% of its original size? It actually looks nicer at 90%, so I want my webpage to default to opening at 90% instead of 100%. I've tried following common approach ...

Set the array back to its initial value of 1 using jQuery and

After making substantial edits to this question, I find myself in need of a reset button for the code. The current item needs to be reset back to 1 so that I can use it again, but the issue lies in the fact that only the current item is reset while the hig ...

Utilizing jQuery AJAX to transfer files from the client side in .NET platform

I need to upload files from the client side using a jQuery Ajax function to a location on a different server, rather than sending them to my application's web server. This is to prevent unauthorized or virus-infected uploads to the application web ser ...

What could be the reason for the compatibility issues between CSS/SASS modules and a third-party library?

I am puzzled by the fact that my sass modules do not affect the third-party component I am using, specifically react-horizontal-scrolling-menu <ScrollMenu selected={selected} scrollToSelected={true} data={items && items.map((item: any) ...

Tips for sending back a response after a request (post | get) is made:

In the service, there is a variable that verifies if the user is authorized: get IsAuthorized():any{ return this.apiService.SendComand("GetFirstKassir"); } The SendCommand method is used to send requests (either as a post or get request): ApiServi ...

Creating a custom route in Node.js using Express for posting content and adding it to a specific user's page

I am currently working on a node.js express project where I am developing a health app for a trainer to manage his clients. The main functionality of the app includes allowing the trainer to access individual client profiles and view their exercise list by ...

Uploading Files with PhoneGap using Ajax

I have been attempting to execute this PhoneGap example for uploading images from a device to a server. // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // functi ...

Tips for positioning content next to a sidebar using basic CSS

I'm having an issue where my content is being hidden behind the sidebar and I want the sidebar to stay fixed on the left side. When I changed position:fixed to float:left in the CSS, it gave me the desired result but the sidebar isn't fixed when ...

Troubleshoot: Problem with iPhone Orientation on Bootstrap Framework

While working on a responsive website design, I encountered an issue that needs addressing. Initially, switching from portrait mode to landscape didn't trigger the expected responsive behavior; instead, it simply zoomed into the site. To prevent this ...

Google Chrome's development tools are unable to detect the manifest

I have a file named manifest.json, and I included it in my HTML using <link rel="manifest" href="./manifest.json">. Despite everything seeming correct, Chrome developer tools are unable to detect my manifest file! This is the content of my manifest ...

What are the potential disadvantages of relocating the login logic from the 'signIn()' function in NextAuth.js?

My experience with NextAuth.js for the first time has led me to realize that signing in using the Credentials provider can be a bit tricky when it comes to error handling. It seems like the default implementation should resemble something along these lines ...

Modify JSON from using single quotes to double quotes using JavaScript

Received a JSON from the backend to the front end that uses single quotes throughout, causing issues with a Magento 2 widget. The JSON structure is as follows: { 'mood': 'happy', 'reason': 'why shouldn't I?'} T ...

Issue with generating WebGL shaders

As I embark on creating a basic application in WebGl and JavaScript following online tutorials, I encountered a peculiar issue while working on some fundamental shaders. The function responsible for generating the shader program presents itself as follows: ...

Transferring the control's identifier to JavaScript using ScriptControlDescriptor

In my CreateChildControls() method, I am creating a control: HtmlGenericControl mycontrol= HtmlGenericControl("li"); mycontrol.ID = "controlID"; controlId = mycontrol.ID; protected virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors() { ...

What is the most effective approach to handling dependencies for an AngularJs 1.x web application?

Right now, I have a bunch of script elements pointing to cdn/local files, which isn't ideal. I'm considering declaring all necessary packages using npm/yarn and serving cdn files with self-hosted fallback. Is this a good idea? Would it be bette ...

Receiving the error "Undefined chart type" when using $q.all with Google Chart API Promise

I am currently working on implementing angular-google-charts using the $http service to retrieve data and display it on charts. I found a helpful tutorial on this blog post: since the GitHub README for angular-google-charts lacks examples of backend data ...

Exploring scroll functionality with Webdriver.io v4

My code is designed to log into the beta version of mediawiki, navigate to the Preferences page, and attempt to click on a button located at the bottom of the page. In order to achieve this, I am utilizing the scroll() function because using only .click() ...

How come .trim() isn't cooperating with me?

I am encountering an issue with this particular piece of javascript. Every time I attempt to use it, nothing is displayed in my div. Instead, it simply adds ?weight=NumberInputed&measure=lbsOrkgs&submit=Submit to the URL. <h2>What size d ...

Facing Issues with User.update in Mongoose and MongoDB

I have been struggling to create a new collection and push it into a specific user's collections array. Despite researching various stackoverflow posts, I am unable to achieve this using either User.update() or User.findOneAndUpdate(). I can confirm t ...