Home > Article > Web Front-end > How to Dynamically Change a Div\'s Background Image with JavaScript?
When working with web pages, it's often necessary to dynamically change the background image of specific elements. JavaScript provides a simple way to achieve this.
In the example you provided, you want to change the background image of a div with the class "ghor" when a specific event occurs (clicking on the div in this case). To do this, you can use the following JavaScript code:
<code class="javascript">function chek_mark() { var el = document.getElementById("a").style.backgroundImage; if (el.includes("Black-Wallpaper.jpg")) { el = "url('cross1.png')"; } else if (el.includes("cross1.png")) { alert("This is working too."); } }</code>
This code will first retrieve the current background image from the div's style attribute. If the image is "Black-Wallpaper.jpg," it will update the background image to "cross1.png" instead. If it's already "cross1.png," it will display an alert.
To implement the above code, you can create a function that handles the click event and calls the chek_mark function:
<code class="html"><div class="ghor" id="a" onclick="change_background()">...</div></code>
<code class="javascript">function change_background() { chek_mark(); }</code>
When the div is clicked, it will call the chek_mark function and update the background image as per your conditions.
The above is the detailed content of How to Dynamically Change a Div\'s Background Image with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!