This tutorial shows how to create a web server with a button that acts as momentary switch to remotely control ESP32 or ESP8266 outputs. The output state is HIGH as long as you keep holding the button in your web page. Once you release it, it changes to LOW. As an example, we’ll control an LED, but you can control any other output.

The ESP32/ESP8266 boards will be programmed using Arduino IDE. So make sure you have these boards installed:
- Installing ESP32 Board in Arduino IDE (Windows, Mac OS X, and Linux)
- Installing ESP8266 Board in Arduino IDE (Windows, Mac OS X, Linux)
Project Overview
The following diagram shows a simple overview of the project we’ll build.

- The ESP32 or ESP8266 hosts a web server that you can access to control an output;
- The output’s default state is LOW, but you can change it depending on your project application;
- There’s a button that acts like a momentary switch:
- if you press the button, the output changes its state to HIGH as long as you keep holding the button;
- once the button is released, the output state goes back to LOW.
Installing Libraries – Async Web Server
To build the web server you need to install the following libraries:
- ESP32: install the ESPAsyncWebServer and the AsyncTCP libraries.
- ESP8266: install the ESPAsyncWebServer and the ESPAsyncTCP libraries.
These libraries aren’t available to install through the Arduino Library Manager, so you need to copy the library files to the Arduino Installation Libraries folder. Alternatively, in your Arduino IDE, you can go to Sketch > Include Library > Add .zip Library and select the libraries you’ve just downloaded.
Code
Copy the following code to your Arduino IDE.
/*********
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-web-server-outputs-momentary-switch/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*********/
#ifdef ESP32
#include <WiFi.h>
#include <AsyncTCP.h>
#else
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>
// REPLACE WITH YOUR NETWORK CREDENTIALS
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
const int output = 2;
// HTML web page
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<title>ESP Pushbutton Web Server</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { font-family: Arial; text-align: center; margin:0px auto; padding-top: 30px;}
.button {
padding: 10px 20px;
font-size: 24px;
text-align: center;
outline: none;
color: #fff;
background-color: #2f4468;
border: none;
border-radius: 5px;
box-shadow: 0 6px #999;
cursor: pointer;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
.button:hover {background-color: #1f2e45}
.button:active {
background-color: #1f2e45;
box-shadow: 0 4px #666;
transform: translateY(2px);
}
</style>
</head>
<body>
<h1>ESP Pushbutton Web Server</h1>
<button class="button" onmousedown="toggleCheckbox('on');" ontouchstart="toggleCheckbox('on');" onmouseup="toggleCheckbox('off');" ontouchend="toggleCheckbox('off');">LED PUSHBUTTON</button>
<script>
function toggleCheckbox(x) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/" + x, true);
xhr.send();
}
</script>
</body>
</html>)rawliteral";
void notFound(AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
}
AsyncWebServer server(80);
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed!");
return;
}
Serial.println();
Serial.print("ESP IP Address: http://");
Serial.println(WiFi.localIP());
pinMode(output, OUTPUT);
digitalWrite(output, LOW);
// Send web page to client
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html);
});
// Receive an HTTP GET request
server.on("/on", HTTP_GET, [] (AsyncWebServerRequest *request) {
digitalWrite(output, HIGH);
request->send(200, "text/plain", "ok");
});
// Receive an HTTP GET request
server.on("/off", HTTP_GET, [] (AsyncWebServerRequest *request) {
digitalWrite(output, LOW);
request->send(200, "text/plain", "ok");
});
server.onNotFound(notFound);
server.begin();
}
void loop() {
}
You just need to enter your network credentials (SSID and password) and the web server will work straight away. The code is compatible with both the ESP32 and ESP8266 boards and controls the on-board LED GPIO 2 – you can change the code to control any other GPIO.
How the Code Works
We’ve already explained in great details how web servers like this work in previous tutorials (DHT Temperature Web Server), so we’ll just take a look at the relevant parts for this project.
Network Credentials
As said previously, you need to insert your network credentials in the following lines:
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
Momentary Switch Button (web server)
The following line creates the momentary switch button.
<button class="button" onmousedown="toggleCheckbox('on');" ontouchstart="toggleCheckbox('on');" onmouseup="toggleCheckbox('off');" ontouchend="toggleCheckbox('off');">LED PUSHBUTTON</button>
Let’s break this down into small parts.
In HTML, to create a button, use the <button></button> tags. In between you write the button text. For example:
<button>LED PUSHBUTTON</button>
The button can have several attributes. In HTML, the attributes provide additional information about HTML elements, in this case, about the button.
Here, we have the following attributes:
class: provides a class name for the button. This way, it can be used by CSS or JavaScript to perform certain tasks for the button. In this case, it is used to format the button using CSS. The class attribute has the name “button”, but you could have called it any other name.
<button class="button">LED PUSHBUTTON</button>
onmousedown: this is an event attribute. It executes a JavaScript function when you press the button. In this case it calls toggleCheckbox(‘on’). This function makes a request to the ESP32/ESP8266 on a specific URL, so that it knows it needs to change the output state to HIGH.
ontouchstart: this is an event attribute similar to the previous one, but it works for devices with a touch screen like a smartphone or table. It calls the same JavaScript function to change the output state to HIGH.
onmouseup: this is an event attribute that executes a JavaScript function when you release the mouse over the button. In this case, it calls toggleCheckbox(‘off’). This function makes a request to the ESP32/ESP8266 on a specific URL, so that it knows it needs to change the output state to LOW.
ontouchend: similar to the previous attribute but for devices with touchscreen.
So, in the end, our button looks like this:
<button class="button" onmousedown="toggleCheckbox('on');" ontouchstart="toggleCheckbox('on');" onmouseup="toggleCheckbox('off');" ontouchend="toggleCheckbox('off');">LED PUSHBUTTON</button>
HTTP GET Request to Change Button State (JavaScript)
We’ve seen previously, that when you press or release the button, the toggleCheckbox() function is called. You either pass the “on” or “off” arguments, depending on the state you want.
That function, makes an HTTP request to the ESP32 either on the /on or /off URLs:
function toggleCheckbox(x) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/" + x, true);
xhr.send();
}
Handle Requests
Then, we need to handle what happens when the ESP32 or ESP8266 receives requests on those URLs.
When a request is received on the /on URL, we turn the GPIO on (HIGH) as shown below:
server.on("/on", HTTP_GET, [] (AsyncWebServerRequest *request) {
digitalWrite(output, HIGH);
request->send(200, "text/plain", "ok");
});
When a request is received on the /off URL, we turn the GPIO off (LOW):
server.on("/off", HTTP_GET, [] (AsyncWebServerRequest *request) {
digitalWrite(output, LOW);
request->send(200, "text/plain", "ok");
});
Demonstration
Upload the code to your ESP32 or ESP8266 board.
Then, open the Serial Monitor at a baud rate of 115200. Press the on-board EN/RST button to get is IP address.

Open a browser on your local network, and type the ESP IP address. You should have access to the web server as shown below.

The on-board LED stays on as long as you keep holding down the button on the web page.
Note: it works the other way around for the ESP8266 because the on-board LED works with inverted logic.

When you release the button, the LED goes back to its default state (LOW).

Watch the next quick video for a live demonstration:
Wrapping Up
In this tutorial you’ve learned how to add event attributes to the buttons on your web server to make them act as momentary switches. This allows you to change the default’s output state as long as you’re pressing the button.
Other projects you may like:
- Display Images in ESP32 and ESP8266 Web Server
- Input Data on HTML Form ESP32/ESP8266 Web Server
- ESP32/ESP8266 Thermostat Web Server – Control Output Based on Temperature
- ESP32/ESP8266: Control Outputs with Web Server and a Physical Button Simultaneously
- ESP32 Web Server using SPIFFS (SPI Flash File System)
Learn more about the ESP32 and ESP8266 with our resources:
- Learn ESP32 using Arduino IDE
- Home Automation using ESP8266
- MicroPython Programming using ESP32/ESP8266
- More ESP32 tutorials …
- More ESP8266 tutorials …
Thanks for reading.
I have tried the ESP32 project first with interest without any adaptation to the script. I noticed that the LED often stays on after a short press of the button and although the button was released. I was planning to use it as a pulse relay but it doesn’t work as expected. Maybe there is another solution for a pulse relay?
Hi Roland,
You can use this example instead: https://gist.github.com/sarasantos/5e60cf40caaf5865cf56f39621501b5c
It’s a web server to control outputs. When you click on, it stays on for 1 seconds and then goes back to the initial state.
You can change the time if needed on line 55.
I hope this helps.
Regards,
Sara
Sorry to bother but you have a small mistake in the code.
The logical values applied to the LED pin should be inverted due to internal pullup!
Thank you
Hi, I made my project work thanks to you and I totally forgot I had made this comment in the beginning of its development. I was just scrolling around to show your website to a colleague and realized that it came out totally wrong! I meant to make a question and not at all doubt your work. In conclusion, nevermind my poor comment.
Thanks a lot for your help and keep up your excelent work!
Hi.
Don’t worry about that.
Thanks for following our work and good luck with all your projects 😀
Regards,
Sara
Leaving…
Hard resetting via RTS pin…
how to fix it?
Hello Edo. That’s the normal behavior and if you see that message your code has been uploaded successfully. Just restart your board to run the newly uploaded code!
Hello,
Can I use this example when the esp32 is configured in AP mode?
Yes.
It will also work in access point mode.
Regards,
Sara
I have to short tap the button on the web page to get the blue on board light to come back on. When I press and hold the button it will stay off, but flickers & wont come back on when I release, unless I give it a short tap, then it comes on (Im using an ESP8266). Is there a modification to make it more reliable/stable ?
Thanks
I tried a PC web page and it works fine. Its just not detecting when I release the button on my touch screen iphone. I can see the graphical button lifting up though when I take my finger off the button. Something about the touch interface
Hi Stephen.
Yes, it must be a problem with the touch interface. However, I don’t know what might be the problem.
Can you try adding the ontouchcancel event to the button element like this:
ontouchcancel = “toggleCheckbox(‘off’);”
?
REgards,
Sara
Hello,
Can someone help me with the coding
since I have the example above (which was very useful)
i would like to put more buttons and GPIO Pins how would I be able to do it i would highly appreciate your help,
FYI: I am new so learning.
there was already an answer:
https://gist.github.com/sarasantos/5e60cf40caaf5865cf56f39621501b5c
this example is much nicer. I am also asking for a hint on how to make some nice keys