I have a ToggleButton like this
I would like to change the color on both sides of the ToggleButton in order to represent light/dark modes
Hi there, I have just started using TMS Web core and would like to incorporate a light/dark mode using a ToggleButton, how can I change the color on both sides of the ToggleButton in order to represent the light/dark mode?
So changing the color on a TWebToggleButton
is a big job! Great question though, because the component doesn't have any properties available to do this in design-time.
First, I made a function to change the color:
procedure ChangeToggleButtonColor(aToggleButton: TWebToggleButton; aColor: TColor);
var
aBtn: TJSHTMLElement;
aBtnSlider: TJSNode;
aBtnColor: String;
begin
aBtnColor := '#' + IntToHex(GetRValue(aColor), 2) + IntToHex(GetGValue(aColor), 2) + IntToHex(GetBValue(aColor), 2) ;
aBtn := aToggleButton.ElementHandle;
aBtnSlider := aBtn.getElementsByClassName(aToggleButton.Name + '_slider').item(0);
asm
aBtnSlider.style["background-color"] = aBtnColor;
end;
end;
You pass in the TWebToggleButton
and the TColor
for it. That will successfully change the color.
Then you need to set a default/starting color for the TWebToggleButton
on the form's OnCreate
event:
procedure TForm1.WebFormCreate(Sender: TObject);
begin
WebToggleButton.Checked := False;
ChangeToggleButtonColor(WebToggleButton, clRed);
end;
And then on the TWebToggleButton
's onClick
event, you need to change the color every time the user clicks on it as well:
procedure TForm1.WebToggleButtonClick(Sender: TObject);
begin
if (TWebToggleButton(Sender).Checked) then
ChangeToggleButtonColor(TWebToggleButton(Sender), clBlue)
else
ChangeToggleButtonColor(TWebToggleButton(Sender), clRed);
end;
And that's it. Now you should have a TWebToggleButton
with a custom color set for both sides (Checked and not Checked).