Only working if side. Else condition doesnt work. whats wrong here?
const onOffCollapsedAds = () => {
let openedTopAdsButton = true;
if (openedTopAdsButton) {
document.querySelector(".collapsed-top-ads").style.opacity = "0";
document.querySelector(".collapsed-top-ads").style.height = "0";
document.querySelector(".collapsed-top-ads-button").textContent =
"Reklamı Göster";
openedTopAdsButton = false;
} else {
document.querySelector(".collapsed-top-ads").style.opacity = "1";
document.querySelector(".collapsed-top-ads").style.height = "auto";
document.querySelector(".collapsed-top-ads-button").textContent =
"Reklamı Kapat";
openedTopAdsButton = true;
}
};
CodePudding user response:
This condition will always be true
:
let openedTopAdsButton = true;
if (openedTopAdsButton) {
//...
}
Because when you define a variable to equal true
, that variable will then equal true
.
It looks like you are expecting the value of the variable to change over time for multiple calls to the onOffCollapsedAds
function. If that's the case then you don't want to re-define the variable and explicitly set it to true
on every call to the function. Instead, define the variable outside the function so its value can persist across function calls:
let openedTopAdsButton = true;
const onOffCollapsedAds = () => {
if (openedTopAdsButton) {
//...
openedTopAdsButton = false;
} else {
//...
openedTopAdsButton = true;
}
};