Home > other >  Change image after onclick on icon
Change image after onclick on icon

Time:03-04

Hello I'm trying to change a image after a onclick into a icon

So for example I've got a div:

<div >
    <i  id="theme-button"></i>

Then I've got a img :

<img src="assets/img/foot.png" alt="" id="imgClickAndChange" >

And I want to change by new image

And this is my js file:

/==================== DARK LIGHT THEME ====================/ 
const themeButton = document.getElementById('theme-button')
const darkTheme = 'dark-theme'
const iconTheme = 'uil-sun'

// Previously selected topic (if user selected)
const selectedTheme = localStorage.getItem('selected-theme')
const selectedIcon = localStorage.getItem('selected-icon')

const getCurrentTheme = () => document.body.classList.contains(darkTheme) ? 'dark' : 'light'
const getCurrentIcon = () => themeButton.classList.contains(iconTheme) ? 'uil-moon' : 'uil-sun'

if (selectedTheme) {
  document.body.classList[selectedTheme === 'dark' ? 'add' : 'remove'](darkTheme)
  themeButton.classList[selectedIcon === 'uil-moon' ? 'add' : 'remove'](iconTheme)
}

themeButton.addEventListener('click', () => {
    document.body.classList.toggle(darkTheme)
    themeButton.classList.toggle(iconTheme)
    document.getElementById("imgClickAndChange").src == "assets/img/rugby.png" //i'm adding this line but not working
    localStorage.setItem('selected-theme', getCurrentTheme())
    localStorage.setItem('selected-icon', getCurrentIcon())
})

I'm adding a specific line but doesn't working, anybody can help me

CodePudding user response:

you are using == a comparison operator, you need =

document.getElementById("imgClickAndChange").src = "assets/img/rugby.png";

CodePudding user response:

themeButton.addEventListener('click', () => {
    document.body.classList.toggle(darkTheme)
    themeButton.classList.toggle(iconTheme)
    document.getElementById("imgClickAndChange").src = "assets/img/rugby.png" // You have to assign it , you have to only use single equals to sign
    localStorage.setItem('selected-theme', getCurrentTheme())
    localStorage.setItem('selected-icon', getCurrentIcon())
})
  • Related