how to enable and disable an onclick function in javascript

Asked

Viewed 60 times

-2

<div onclick="theme()" class="theme">
    <img id ="theme"src="elements/dark.svg"/>
</div>```

______________________________________________

let bodydark = document.getElementById('body');

function theme() {
    document.getElementById("theme").src="elements/light.png";
    change_theme();
}

function change_theme() {
    bodydark.style.background = 'var(--overlay)';
    
    let div_wrapper = document.getElementById("q1").style.backgroundColor = '#091b38';
    let div_wrapper1 = document.getElementById("q2").style.backgroundColor = '#091b38';
    let div_wrapper2 = document.getElementById("q3").style.backgroundColor = '#091b38';
}

Basically this code when clicking on div a function Theme() changes the src of the div and changes the theme to dark, I would like it to be possible to click again on the div back to default, similar to the change theme of google Chrome. Please help me out! I don’t know if the right word would be to deactivate the existing function, but I tried to put 2 functions inside the div, one to change the theme and the other to give a Reloader on the page, but one kind of clashes with the other and runs both at the same time and the page gets dark and recharges so on!

2 answers

-2

I think the best way to do this would be to alternate the div class, between dark css and light css css:

.dark_theme{
    color: #ffffff;
    background-color: #000000
}

.light_theme{
    color: #000000;
    background-color: #ffffff
}

and no js

let isDark = false;
function theme() {
    if(isDark){
        document.getElementById("theme").src="elements/light.png";
        bodydark.classList.toggle("light_theme")
        isDark = false;
        return;
    }
    document.getElementById("theme").src="elements/dark.png";
    bodydark.classList.toggle("dark_theme")
    isDark = true;
}

css is just an example you could put everything you want to change from body in case and also don’t forget to start the div you want to change with one of these classes

  • Yeah, good idea, thanks!

-2

You can add a flag in your div and in the Theme function just check. If the flag is dark you light arrow and vice versa. for example:

function theme(element) {

    console.log(element.getAttribute('flag'));

    if (element.getAttribute('flag') == 'dark'){
        document.getElementById('theme').setAttribute('src', 'elements/light.png');
        element.setAttribute('flag', 'light');
    }else{
        document.getElementById('theme').setAttribute('src', 'elements/dark.svg');
        element.setAttribute('flag', 'dark');
    }

}
<div onclick="theme(this)" class="theme" flag="dark">
    <img id="theme" src="elements/dark.svg"/>
</div>

  • It worked here, exactly what I wanted. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.