简体   繁体   中英

Changing the background colour of a button (On/Off)

I have reviewed This Question but I am not using angular.

Here is my code so far:

<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>Bx</button>
<button id='By' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>By</button>
<button id='Bz' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>Bz</button>

With my JS like this:

function toggleClickedBuz( bizStr , id ) {
    if(clickedBusinesses.includes(bizStr)){
       // removing duplicate element from that array, dependant on button pressed
       clickedBusinesses = clickedBusinesses.filter( cb => cb !== bizStr );
       document.getElementById( id ).style.backgroundColor='white';
    }else{
        // else push it to the array
       clickedBusinesses.push(bizStr)
       document.getElementById( id ).style.backgroundColor='red';
    }
    console.log(clickedBusinesses)
}

But I am getting this error:

Uncaught TypeError: Cannot read property 'style' of null

Despite having this in my CSS:

.canvas .button-box button {
    border-radius: 2px;
    width: 10vw;
    margin-top: 0.5vh;
    background-color: whitesmoke;
}

Any advice?

Simple, You don't need # in toggleClickedBuz("Bx", "#Bx") . Put id without # . The function getElementById() already refers the id. So you don't need to specify using # .

Your HTML should be like

<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>Bx</button>
<button id='By' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>By</button>
<button id='Bz' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>Bz</button>

Given following HTML

<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "#Bx")'>Bx</button>

You are passing #Bx as id argument to your toggle function. This results in the js call:

document.getElementById("#Bx");

But the getElementById function does not require the # prefix. Try to change your HTML to

<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>Bx</button>

to hotfix your current problem

You do not need # in your button. This much is enough:

<button id='Bx' type="button" onclick='toggleClickedBuz("Bx","Bx")'>Bx</button>
<button id='By' type="button" onclick='toggleClickedBuz("Bx","Bx")'>By</button>
<button id='Bz' type="button" onclick='toggleClickedBuz("Bx","Bx")'>Bz</button>

# is a CSS selector whuch selects your HTML id elements. You can reference them in your CSS in this manner:

#Bx {
  color: #AAAAAA;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM