Home > Blockchain >  How to toggle between two background images for a div having an event listener
How to toggle between two background images for a div having an event listener

Time:08-24

It's a to do list and here's the JS I'm stuck into -

function taskCheck() {
    let taskCheckboxImg = this.style.backgroundImage;
    if(taskCheckboxImg=="url('img/uncheck.png')") {
        taskCheckboxImg="url('img/check.png')";
    } else {
        taskCheckboxImg="url('img/uncheck.png')";
    }
}

I want to toggle between check and uncheck by changing the background image when clicked but the if statement doesn't seem to work. Perhaps it doesn't change the background image property in the 4th line.

I could have done this with a regular checkbox but it doesn't seem to have editable properties in CSS. Help!

CodePudding user response:

You are assigning the value to a variable, instead you need to change the value of the CSS property after each condition like

this.style.backgroundImage = "url('img/check.png')";

Also, you are using this, which refers to the current object, so make sure you have the this context available from wherever you call taskCheck() function


You function after the change should look like below

function taskCheck() {
    let taskCheckboxImg = this.style.backgroundImage;
    if(taskCheckboxImg=="url('img/uncheck.png')") {
        this.style.backgroundImage="url('img/check.png')";
    } else {
        this.style.backgroundImage="url('img/uncheck.png')";
    }
}

CodePudding user response:

You can also do something like below:

function taskCheck() {
    const backgroundImg = document.querySelector('.backgroundImg');
    backgroundImg.classList.toggle('uncheck-image');
    backgroundImg.classList.toggle('check-image'); 
}
 taskCheck();
.backgroundImg{
  width:100px;
  height:100px;
}
.uncheck-image{
background-image: url('https://via.placeholder.com/100');
}

.check-image{
background-image: url('https://via.placeholder.com/50');
}
<div ></div>

CodePudding user response:

const myDiv = document.querySelector('div')
myDiv.addEventListener('click', taskCheck)

function taskCheck(e) {
    let taskCheckboxImg = e.target.style.backgroundImage;

    if(taskCheckboxImg=='url("https://picsum.photos/id/200/200/200")') {

            // you have to change css property like this
        e.target.style.backgroundImage='url("https://picsum.photos/id/300/200/200")';
    } else {
    console.log(taskCheckboxImg)
    
        e.target.style.backgroundImage='url("https://picsum.photos/id/200/200/200")';
    }
}
div{
  width: 200px;
  height: 200px;
  background-size: cover;
}
<div style="background-image:url('https://picsum.photos/id/200/200/200')"></div>

  • Related