5 Ways to Allow "Only One Click" in Javascript - Beginner’s Guide

5 Ways to Allow "Only One Click" in Javascript - Beginner’s Guide

Welcome to a beginner’s tutorial on how to allow only one click in Javascript. So you have a button or element that says “click here to do something”, but want to prevent the user from clicking it multiple times. Well, there are actually a number of ways to implement that “one-click protection”

INTRODUCTION

Welcome to a beginner’s tutorial on how to allow only one click in Javascript. So you have a button or element that says “click here to do something”, but want to prevent the user from clicking it multiple times. Well, there are actually a number of ways to implement that “one-click protection”:

  • Disable the button after the user clicks on it.
  • Use a flag to indicate “now processing”, don’t process if this flag is on
  • Remove the on-click attribute.
  • Attach an on-click event listener, and detach it after the click.
  • The unorthodox method – Change the handling on-click function.

QUICK NOTES

There is nothing to install, so just download and unzip into a folder. If you spot a bug, please feel free to comment below.

ONE CLICK PROTECTION

With that, let us now move into the mechanisms we can put in place for “one-click protection”.

1. DISABLING THE BUTTON

<!DOCTYPE html>
<html>
  <head>
    <title>
      Disable Button
    </title>
    <script>
      function doSomething () {
        // Disable the button
        document.getElementById("myButton").disabled = true;

        // Do your processing here
        alert("Something is done!");

        // Re-enable after processing if you want
        // document.getElementById("myButton").disabled = false;
      }
    </script>
  </head>
  <body>
    <!-- Remember to give the button a unique button -->
    <input type="button" id="myButton" value="Click Here To Do Something" onclick="doSomething()"/>
  </body>
</html>

It’s as simple as that, we manually disable the button with document.getElementById("myButton").disabled = true when it is clicked. But yep, take note this will only work on buttons:

  • <input type="button"/>
  • <input type="submit"/>
  • <button>

2. PROTECTION FLAG

<!DOCTYPE html>
<html>
  <head>
    <title>
      Protection Flag
    </title>
    <script>
      // Flag for "now processing" or "already clicked".
      var clicked = false;
      function doSomething () {
        // Will only start if clicked is false
        if (!clicked) {
          // Set clicked to true
          clicked = true;

          // Do your processing here
          alert("Something is done!");

          // Re-enable after processing if you want
          // clicked = false;
        }
      }
    </script>
  </head>
  <body>
    <div onclick="doSomething()">
      Click Here To Do Something
    </div>
  </body>
</html>

So what if we are not working with buttons? This is one of the possible mechanisms:

  • First, we create a “protection” flag var clicked = false.
  • Then in our onclick handling function, we will only proceed if (!clicked).
  • Should be Captain Obvious by now – We will set clicked = true to prevent further clicks from processing.

3. REMOVE ON-CLICK ATTRIBUTE

<!DOCTYPE html>
<html>
  <head>
    <title>
      Remove On-click
    </title>
    <script>
      function doSomething () {
        // Remove onclick
        var element = document.getElementById("myDiv");
        element.onclick = "";

        // Do your processing here
        alert("Something is done!");

        // Re-enable after processing if you want
        // element.onclick = doSomething;
      }
    </script>
  </head>
  <body>
    <div id="myDiv" onclick="doSomething()">
      Click Here To Do Something
    </div>
  </body>
</html>

The above is actually not the preferred “orthodox” method, this one is. We simply remove the on-click from the element with a one-liner document.getElementById("myDiv").onclick = ""

4. ATTACH & DETACH EVENT LISTENER

<!DOCTYPE html>
<html>
  <head>
    <title>
      Attaching Detaching Click Event
    </title>
    <script>
      // Your onclick function as usual
      function doSomething () {
        // Detach click listener
        var para = document.getElementById("myParagraph");
        para.removeEventListener("click", doSomething);

        // Extra - Change the text if you want
        para.innerHTML = "You clicked";

        // Do your processing here
        alert("Something is done!");

        // Re-enable after processing if you want
        // para.addEventListener("click", doSomething);
      }

      // Wait for page to be fully loaded
      window.addEventListener("load", function(){
        // Attach on-click
        document.getElementById("myParagraph").addEventListener("click", doSomething);
      });
    </script>
  </head>
  <body>
    <!-- Remember to give the button a unique button -->
    <!-- NOTE : No onclick in HTML, assign with Javascript instead -->
    <p id="myParagraph">
      Click Here To Do Something
    </p>
  </body>
</html>

Now, this one may seem to be a little more long-winded, but it will make sense in the long run as you learn more about event listeners and the sequence of how the scripts and elements are loaded. Not going to shove that in your face right now, but just know that there is something called addEventListener() and removeEventListener().

5. UNORTHODOX FUNCTION SWITCHER

<!DOCTYPE html>
<html>
  <head>
    <title>
      Funky function switcher
    </title>

    <style>
      /* SHAKE ANIMATION - JUST FOR FUN */
      /* https://www.w3schools.com/howto/howto_css_shake_image.asp */
      @keyframes shake {
        0% { transform: translate(1px, 1px) rotate(0deg); }
        10% { transform: translate(-1px, -2px) rotate(-1deg); }
        20% { transform: translate(-3px, 0px) rotate(1deg); }
        30% { transform: translate(3px, 2px) rotate(0deg); }
        40% { transform: translate(1px, -1px) rotate(1deg); }
        50% { transform: translate(-1px, 2px) rotate(-1deg); }
        60% { transform: translate(-3px, 1px) rotate(0deg); }
        70% { transform: translate(3px, 1px) rotate(-1deg); }
        80% { transform: translate(-1px, -1px) rotate(1deg); }
        90% { transform: translate(1px, 2px) rotate(0deg); }
        100% { transform: translate(1px, -2px) rotate(-1deg); }
      }
      #myButton.shaker {
        animation: shake 0.5s;
        animation-iteration-count: infinite;
      }
    </style>

    <script>
      // Function that does idle Easter eggs
      function doIdle () {
        // Shake the button maybe?
        // Flash it?
        document.getElementById("myButton").classList.add("shaker");
      }

      // Normal function
      function doSomething () {
        // Switch funky to do the idle function
        funky = doIdle;

        // Do your processing here
        alert("Something is done!");
      }

      // Funky switching function
      var funky = doSomething;
    </script>
  </head>
  <body>
    <input type="button" id="myButton" value="Click Here To Do Something" onclick="funky()"/>
  </body>
</html>

This last method is not actually “single click protection”, but switching to do something else completely after the first click.

  • Create your first function function doSomething() – This one will do your “main intended processing”.
  • Create your second function function doIdle() – This one can be a simple “please wait, now processing” message, or an Easter egg to scare the user.
  • Then create a variable, point it to the first function var funky = doSomething.
  • In the first line of function doSomething(), switch funky = doIdle.
  • That’s about it. Finally,  just point the onclick of the button to funky.

WHICH IS THE BEST?

That’s all for this short tutorial, and here is a small section on some extras and links that may be useful to you.

All of the above methods work just fine, so whichever that suits your needs. But if you are doing this “one-click protection” to prevent things like multiple registrations. Please remember to do your checks on the server-side as well, check if the given user name or email is already registered.

Thank you for reading ! I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.

Javascript tutorial Programming Developer

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

9 JavaScript Tricks making programming life much easier

Making my programming life much easier and they look pretty cool in the editor. 9 JavaScript Tricks I Live By. Destructuring, Dynamic Property Names, map(), filter(), Template Literals, Short Circuit Conditionals, The Spread Operator Spreads values from one (or more) array(s) into another to form a single array, some(), Returns true if at least one of the elements in your array satisfies the condition you’re passing in. False otherwise, includes().

Automatic semicolon insertion (ASI) in JavaScript

Semicolons and Automatic Semicolon Insertion are two of the most misunderstood topics in JavaScript. In this tutorial, you will learn about what ASI is. You will also learn about the rules that determine where semicolons are required.

JavaScript Tutorial: Function in JavaScript

Functions are very important and useful in any programming language as they make the code reusable A function is a block of code which will be executed only if it is called.

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

JavaScript Programming Tutorial - Full JavaScript Course for Beginners. Learn JavaScript from basic to advanced. JavaScript is the programming language of HTML and the Web.

How to start writing less error-prone code in JavaScript

How to start writing less error-prone code in JavaScript - Everything in JavaScript is an object!’. We said that this assertion is false. Many things in JavaScript can behave like an object, but that doesn’t mean it’s the object. We can say we have three types of objects (objects, functions and arrays) in JavaScript.