Guide on updating BgImage dynamically through JavaScript

I've been exploring a way to dynamically update the background image of an HTML document using JavaScript. While I am familiar with hardcoding the links, I'm interested in loading it from a variable URL that I specify. Here is what currently works:

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">Set background image</button>

<script>
function myFunction() {
  document.body.style.backgroundColor = "#f3f3f3";
  document.body.style.backgroundImage = "url('https://i.imgur.com/B95LprK.jpg')";
}
</script>

</body>
</html>

However, this is what I actually need:

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">Set background image</button>

<script>
var imageLink = 'https://i.imgur.com/B95LprK.jpg'
function myFunction() {
  document.body.style.backgroundColor = "#f3f3f3";
  document.body.style.backgroundImage = "url(imageLink)";
}
</script>

</body>
</html>

Does anyone have any suggestions on how to achieve this?

Answer №1

If you want to easily insert variables into a string, consider using template literals with backticks ` `.

var pictureLink = 'https://i.imgur.com/B95LprK.jpg';
document.body.style.backgroundImage = `url(${pictureLink})`;

Another method is to concatenate strings using the + operator.

var pictureLink = 'https://i.imgur.com/B95LprK.jpg';
document.body.style.backgroundImage = "url(" + pictureLink + ")";

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

An unconventional web address was created when utilizing window.location.hostname

I've encountered an issue while trying to concatenate a URL, resulting in unexpected output. Below you'll find the code I tested along with its results. As I am currently testing on a local server, the desired request URL is http://127.0.0.1:800 ...

Submit the form first and then proceed to download another webpage

I have an idea for creating a tool that can accomplish two tasks: Set the language and date on a specific web form: , and Download the text from another page on the same site while retaining these settings. For example, . This tool should simulate a ...

Is it possible to assign a property value to an object based on the type of another property?

In this illustrative example: enum Methods { X = 'X', Y = 'Y' } type MethodProperties = { [Methods.X]: { x: string } [Methods.Y]: { y: string } } type Approach = { [method in keyof Method ...

Error: Incorrect data input in Django calendar form

I have a DateForm class defined in my form.py file: class DateForm(forms.Form): date = forms.DateTimeField( input_formats=['%m/%d/%Y %H:%M'], widget=forms.DateTimeInput(attrs={ 'class': 'form-control dateti ...

Encountering an issue with sending a direct message on Twitter through OAuth

I am currently developing a JavaScript script to work alongside my C++ application for sending direct messages to users. The script is responsible for constructing the request that I send out. However, whenever I make a request, I keep getting errors like ...

Utilizing JavaScript within my WordPress site

I'm experiencing some issues with my JavaScript code in WordPress. I have been trying to use the following code on my page, but it doesn't seem to work properly. Can someone please guide me on how to integrate this code within my WordPress page? ...

CSS Panel Assignments

I am attempting to split the screen where 80% is dedicated to displaying a Google map at the bottom, and the remaining 20% displays content in a div with the ID '#data' at the top. However, the code below does not seem to achieve this layout as i ...

Discrepancies observed between Protractor local and global installations

I've been tackling a tough issue with two other developers for almost 24 hours now. We have a conf.js file that runs smoothly when invoked in Terminal with the command protractor conf.js using the globally installed version of Protractor. Each test pa ...

Troubleshooting issue with DOM not refreshing after making a $http POST request in a MEAN

I am working on an app that interacts with a Mongo database through CRUD operations. Currently, I have a form input where users can add elements, and I want these elements to appear below the form in real-time as they are added. However, at the moment, the ...

Adding a shadow to a 3D model with Threebox

I am currently working on a project utilizing threebox js and attempting to incorporate shadows for imported 3D models. Following the guidelines outlined in the documentation here. When creating an object, I adjust the property to TRUE (code snippet provid ...

Is there a way to extract the text that is displayed when I hover over a specific element?

When I hover over a product on the e-commerce webpage (), the color name is displayed. I was able to determine the new line in the HTML code that appears when hovering, but I'm unsure how to extract the text ('NAVY'). <div class="ui ...

Using the React JS useState hook to toggle the state of a JSON object containing an array when a checkbox is clicked

When I submit my state as a stringified variable from a form to a POST request via a lamda server, it gets parsed and sent to sendgrid for templating. To loop over specific parts (multiple checkboxes) in JSON format, each with the same key but different va ...

vue 3 custom global directive for detecting clicks outside

My goal is to change the row value to 10 when clicking on <textarea>, and revert it back to 6 if clicked outside of the element. I am new to Vue.js 3 and struggling with this issue, particularly regarding directives. <template> <div> ...

What is the correct method for handling images in HTML and CSS?

Hey there! Just playing around on jsfiddle and wanted to share this Destiny-inspired creation: http://jsfiddle.net/3mfnckuv/3/ If you're familiar with Destiny, you'll see the inspiration haha.. But here are a few questions for you: 1) Any ide ...

Use jQuery to insert items into the text box

When I drag li elements into the textbox, they are arranged in the middle. How can I arrange these elements at the beginning? I am using Foundation. Is there a possible issue? This is my jQuery code: <script type="text/javascript"> $(function( ...

Having trouble with integrating Firebase and Vue database

While attempting to integrate Firebase with my Vue 4 application, I encountered the following error: Uncaught TypeError: db__WEBPACK_IMPORTED_MODULE_1_.default.database is not a function The versions I am using are: "firebase": "^9.0.0&qu ...

Is it possible to retrieve the index of a chosen v-select option within Vuetify?

Exploring Vuetify for the first time, I'm encountering an issue with obtaining the index of a selected option on the v-select component. My goal is to populate a text field based on the option that is clicked once I have the index. I am fetching an ...

Height of a React Component

I have developed a React component for the homepage of my React application. Utilizing React Router, I am able to navigate through different components on the site. The issue I'm facing is that the homepage component does not occupy the entire page ex ...

Vue.js - Axios Get request received an object response

My current project is built on Vue.js and I am using Flask for the API. The issue arises when trying to make an axios.get request - the API returns an object 'Object'. Interestingly, when testing the same request in Postman, it works fine and ret ...

I desire to rearrange the items within several arrays of lists

I currently have an array set up like this 0: (5) ["2", "X", "8", "11", "15"] 1: (5) ["1", "5", "X", "X", "14"] 2: (5) ["X", "4", "7", "10", "13"] 3: (5) ["X", "3", "6", "9", "12"] My goal is to swap the position of the digit 1 with the position of digi ...