Button text toggle on click

In the last lesson, we added two buttons. One changes its text when clicked, and the other closes the current window. In this section, we will add slightly more complex logic to the first button. Each click toggles the button text back and forth. This lesson mainly covers basic Pascal syntax.

Open the project we created earlier

You can edit the click event function directly in the PAS file, or navigate to the first button’s event function using the method below.

Replace the event function code with the following snippet

procedure TForm1.Button1Click(Sender: TObject);
{ Use the button Tag property to record state and implement text toggle }
begin
  // Judge Tag value: 0 = default state, 1 = toggled state
  if Button1.Tag = 0 then
  begin
    Button1.Caption := 'Press again';  // Modify button display text
    Button1.Tag := 1;                  // Mark state as 1
  end
  else
  begin
    Button1.Caption := 'Press';        // Restore original text
    Button1.Tag := 0;                  // Reset state marker to 0
  end;
end;Code language: JavaScript (javascript)
Steps to locate the button click event

Open your saved Lazarus project and switch to the Form1 design view. Click the button labeled Press (Button1) on the form.

With the control selected, open the Events tab in the Object Inspector on the right side.

Locate the OnClick click event row. Click the input box on its right, then click the trailing ... ellipsis button to auto-jump to the corresponding function in the code editor.

Clear all original code, paste the complete code below, save the project, compile and run the program. Click the button to toggle its text back and forth.

  1. Tag Property: An integer property built into all form controls, used to store custom numeric flags. We only use two states: 0 and 1 here.
  2. First click: Tag=0 → Text changes to Press again, Tag set to 1
  3. Second click: Tag=1 → Text reverts to Press, Tag reset to 0
  4. Repeated clicks keep toggling the text, creating an on/off switch effect.

The code above leverages the button’s Tag property to store its state and realize the toggle function.

Running Demo

Button text toggle on click

Leave a Reply

Your email address will not be published. Required fields are marked *