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

Patricia Arquette
Release: 2024-11-02 09:24:31
Original
182 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!