Using a background GIF in JavaScript to dynamically alter CSS properties

I'm attempting to modify the CSS of my website so that when a user clicks on a div, the background changes to a gif. However, I am having trouble accomplishing this using JavaScript!

Here is my code:

 function easterFun(){
     var changeBG = document.getElementById("body");
     changeEaster.setAttribute("style","background-image:url(eatser.gif)")

In addition, my div is not responding when clicked and the code is not executing. Can someone please help me identify the issue?

Welcome to the Holiday Spirit website!!!

<div  id="easter"onclick="easterFun()" style = "cursor: pointer">Easter!</div>
<div id="xmas" onclick="xmasFun()">Christmas</div>

</body>
</html>

Answer ā„–1

Utilize style.cssText or style.backgroundImage

For instance:

function springCelebration(){
     var changeBG = document.getElementById("body");
     changeBG.style.cssText = "background-image: url(spring.gif)";
}

Alternatively:

function springCelebration(){
     var changeBG = document.getElementById("body");
     changeBG.style.backgroundImage = "url(spring.gif)";
}

Note:

document.getElementById only selects elements with ID attributes (e.g. <div id="body">)

To target the body element, use: document.body (or

document.getElementsTagName("body")[0]
), for example:

function springCelebration(){
     var changeBG = document.body;
     changeBG.style.backgroundImage = "url(spring.gif)";
}

Answer ā„–2

Feel free to give this a shot

updateChristmas.style.backgroundImage = "url(christmas.gif)";

Answer ā„–3

Almost there! Make sure to switch getElementById with getElementsByTagName and make sure your variables match:

function easterMagic(){
     document.getElementsByTagName("body")[0].setAttribute("style","background-image:url(eatser.gif)");
}

getElementsByTagName gives back an array of objects, hence why we use [0] after the function call.

I've also left out the variable declaration in the example above for simplicity.

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

Guide on integrating React.js into an HTML development webpage

I can't seem to get this code to work properly. I have saved it as an .html file on my computer, but it's not displaying anything when I try to open it in Google Chrome. <DOCTYPE! html> <html> <head> <script src= ...

Could javascript be considered insufficient for conducting complex fluid simulations due to its speed limitations?

Currently, I am tackling the challenge of implementing a small fluid simulation in P5js. My attempt involved rendering 20,000 squares with random colors, but I only achieved a frame rate of 2.xxx. var sim; var xdim = 200; var xLength; var ydim = 100; var ...

Before beginning my selenium scripts, I need to figure out how to set an item using Ruby in the browser's localStorage

Before running my selenium scripts, I am attempting to store an item in the browser's localStorage. I attempted to clear the local storage using this command: driver.get('javascript:localStorage.clear();') This successfully cleared the lo ...

Tips for effectively invoking an MVC Controller using AJAX

I am currently working on initiating an AJAX call to a controller ActionResult within the MVC framework. While I have experience with AJAX, I am relatively new to MVC. I have set up an AJAX call in a separate .js file that is triggered by a button click ev ...

Ensure the links open in a new tab when using Firefox

Iā€™m working on a new Firefox extension and I want to ensure that all links on a webpage open in a new tab. Any suggestions on how I can achieve this? ...

Struggling to properly align a dynamically changing image in the center

I am struggling to vertically center an image on my webpage. Since I don't know the dimensions of the image beforehand, my only options are using tables or css tables. Even after trying to use css tables, I still can't seem to get the image cent ...

Showing content from a JavaScript variable once a button has been clicked

Imagine you are using express.js and have a JavaScript variable embedded in an ejs file like this: <%= someVariable %> How can you display the value from this variable on the same page, for instance within a bootstrap modal element (check out https: ...

The function of the keyboard being activated after the implementation of document.execCommand("copy") on an iOS mobile device's webview

Is there a way to copy text in an iOS mobile webview without the keyboard appearing? document.getElementById("code").select(); document.execCommand("copy"); If anyone has a solution, your help would be much appreciated! ...

Using SetTimeOut in THREE JS

I'm currently working on a project for my master's degree that involves creating a space invaders game using three.js. While the project is progressing well, I've encountered a problem with my aliens (THREE.Mesh object) being able to fire r ...

"Stylish social media buttons affixed to the top of an HTML and CSS

Struggling to position three social media buttons on my page, but they keep appearing at the top of the page. I want them in a straight line centered within the header. No matter what I try, the icons remain stuck at the top. <!DOCTYPE html> <H ...

Link directly to a specific slide within the JQuery Revolution Slider

I have integrated the JQuery revolution slider into my website and it's working well. However, I am looking for some guidance on how to link to a specific slide within the slider. My goal is to have the slider scroll to a particular slide when a user ...

Calculate the quantity of items within a JSON object that possess specific characteristics

Here is some JSON information: {"people": [ { "firstName" : "Paul", "lastName" : "Taylor", "hairCount": 2 }, { "firstName" : "Sharon", "lastName" : "Mohan", "hairCount": 3 }, { "firstName" : "Mohan", "lastName" : "Harris", "hairCount": 3 }, ...

Server has sent an Ajax response which needs to be inserted into a div

I have a modal window that sends a POST request to the server. Before returning to the view, I store some information in ViewData. Here's an example of what I'm doing: ViewData["Msg"] = "<div id=\"msgResponse\" class=\"success ...

What is the appropriate semantic to apply to the members of a search result list?

I have an image that illustrates my goal: https://i.sstatic.net/xDLRA.png The "Search Results" Title is a h2 in terms of semantics. The "Search Result Title 2018" would be a h3. My query pertains to how the elements "Date & Time", "Fees", "Credit", an ...

Table borders not displaying properly in Chrome when cells are hidden

I'm dealing with a peculiar issue regarding the display of borders in Chrome when individual cells are hidden within an HTML table. The borders disappear, despite being defined for the row and table elements. Does anyone have experience with this spec ...

Having trouble with implementing Nested routes in Vuejs?

main.js import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import HelloWorld from "./components/HelloWorld"; import User from " ...

Participant joins in the game table and reacts

I am looking to set up a table where players can join and have their usernames displayed at the bottom of the screen just like in other games. How can I achieve this? export const GameStart = (props) => { const params = useParams(); const gameID = p ...

A Vuex action that produces a promise never fulfills or rejects

I am currently enhancing my API service within my VueJS application by utilizing Vuex. As part of this process, I am restructuring certain aspects to streamline error handling and cleanup procedures. However, I am encountering difficulty in correctly chain ...

Issue Encountered While Trying to Upload File Using Ajax

I have been encountering an issue with uploading a file using Ajax. My goal is to upload a single file only. Below are the snippets of code that I have utilized. HTML & Ajax $(document).ready(function(){ $("input:submit").on('click', func ...

Is there a way to change the value of "this. props.history.location.pathname" programmatically without causing a page refresh?

I'm currently developing a small extension for my map-based project. This extension is intended to display the latitude and longitude of a place in the URL like this whenever the user changes location. The issue lies in my inability to modify the pat ...