Home  >  Article  >  Web Front-end  >  How to Toggle a Div\'s Background Image with JavaScript?

How to Toggle a Div\'s Background Image with JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 09:24:31182browse

How to Toggle a Div's Background Image with JavaScript?

Changing Background Image of a Div Using JavaScript

In your JavaScript code, you're using the wrong syntax to manipulate the background image of a div element. el.url() is not a valid function for this purpose. Here's how you can correctly change the background image:

<code class="javascript">function chek_mark() {
  var backgroundImage = document.getElementById("a").style.backgroundImage;

  if (backgroundImage.includes("Black-Wallpaper.jpg")) {
    document.getElementById("a").style.backgroundImage = "url(cross1.png)"; // Replace with the new image path
  } else {
    document.getElementById("a").style.backgroundImage = "url(Black-Wallpaper.jpg)"; // Reset to the original image path
  }
}</code>

Modify your chek_mark() function with this code. When you click on the div element with the "ghor" class, it will toggle the background image between "Black-Wallpaper.jpg" and "cross1.png."

The above is the detailed content of How to Toggle a Div\'s Background Image with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn