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.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

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

What’s new in HTML6

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

What is new features in Javascript ES2020 ECMAScript 2020

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

JavaScript is the programming language of HTML and the Web. JavaScript is easy to learn. This tutorial will teach you JavaScript from basic to advanced. JavaScript Programming Tutorial - Full JavaScript Course for Beginners

Watch this JavaScript tutorial for beginners to learn JavaScript programming from scratch. 👍

⭐️Course Contents⭐️

01 | Introduction

Get an introduction from Bob, as he kicks off the course, sets expectations, and gives you a little guidance for the road ahead.

02 | Setting Up the Development Environment

See how to install Node and Visual Studio Code, and learn why you need each. Watch as Bob writes a first tiny line of code to make sure that the installation is ready.

03 | Basic JavaScript Syntax

Hear about the basics of the JavaScript syntax, including how JavaScript is executed, how to create a properly formed statement, and more.

04 | Variables

Learn what variables are and how to declare, initialize, set, and get values from them.

05 | Data Types

JavaScript works with data types differently than other programming languages do. Learn from Bob as he explains some of the most basic data types and how to determine the type held by a variable.

06 | Type Coercion and Conversion

Sometimes you need to explicitly convert the data type of a value into a different data type. Sometimes JavaScript will do this automatically for you. Bob explains how and why this happens.

07 | Expressions and Operators

Learn how to spot a well-formed expression and how to compose expressions through the combination of operators and operands.

08 | Arrays

Watch as Bob demonstrates how to use arrays, how to add/remove elements of an array, how to access elements of an array using the index, how to get the number of elements in an array, and more.

09 | Function Declaration

Get an introduction to functions, as Bob shows you one way to define a function, how to call the function, how to pass parameters into a function, how to return values from a function, and more.

10 | Function Expressions

Sometimes a function declaration is more than you need. Get details in this lesson, as Bob demonstrates how to use a function expression and how to create an immediately invoked function expression.

11 | Decision Statements

Learn how to add logic to your applications by testing conditions using if / else statements, switch / case statements, and the ternary operator.

12 | Iteration Statements

Watch as Bob introduces the For and While statements, which enable you to loop through lists of values and perform operations on them.

13 | Basics of Scope

Hear an explanation of the notion of the lifetime of variables and their reach into other code blocks, in this discussion of scope.

14 | Returning Functions from Functions

As a building block toward a more sophisticated approach to building JavaScript applications, see how you can return functions from functions.

15 | Object Literals

Objects contain properties and functions that describe attributes of the object and its behavior, respectively. Watch as Bob demonstrates how to create object literals.

16 | Module Pattern and Revealing Module Pattern

Learn how to introduce variables and functions without leaving an unnecessarily large footprint on the global scope.

17 | Closures

Closures allow developers to bind functions to their execution context, including variables, so you can build specialized versions of functions. Learn how closures work and how to create them.

18 | this Keyword

Get the details on the "this" keyword, which causes a lot of confusion for JavaScript developers. Listen as Bob explains what this mysterious object is and how to bend it to your will.

19 | Destructuring

See how to use destructuring, a new feature in JavaScript that allows you to unpack array elements or object properties in a concise syntax.

20 | String Template Literals

Learn about the new string template literal syntax to enable string interpolation, multi-line string formatting, and more.

21 | Regular Expressions

Working with string data, Bob explains how use regular expressions to determine such things as whether a string matches a specific pattern or whether an instance of the pattern exists in a string.

22 | Built-In Natives

Join Bob as he examines native, built-in JavaScript functions that return objects that box the primitive types in order to provide additional helper methods on your values.

23 | Constructor Function Calls with the new Keyword

Learn how constructor functions work, see how to make key distinctions in what they are, and find out why they’re helpful.

24 | Objects and the Prototype Chain

Moving past the absolute beginner matter, listen in as Bob explains how objects work in JavaScript and how you can create an object that is linked to another object.

25 | JavaScript Classes

Bob demonstrates how “syntactic sugar” works on top of the existing functions and prototype chaining to help JavaScript resemble more traditional object-oriented programming languages.

26 | Arrow Functions

The latest version of JavaScript added arrow functions, a shorthand syntax for creating functions. Watch as Bob demonstrates how to create them and shows where they’re useful.

27 | Truthy and Falsy Values

Listen is as Bob circles back to topics that are important (but didn’t easily fit into earlier topics) and looks at the odd way in which JavaScript evaluates certain expressions as truthy and falsy.

28 | null Type

Similar to the undefined primitive type, the null type represents a variable that has no reference to an object when one was expected. Hear an explanation of how and why we should think about nulls.

29 | Date Objects

No discussion of JavaScript would be complete without understanding the Date built-in native function which provides properties and methods for working with dates and times.

30 | String Methods

The built-in native String function provides several very useful methods for manipulating and evaluating strings. Watch Bob demonstrate how to use a few of the most useful ones.

31 | Array Methods

We’ve worked with arrays throughout this course. Now Bob takes a few minutes to show you some of the most useful methods provided by the Array built-in native function.

32 | Error Handling with Try Catch

See how to wrap a try/catch/finally statement around potentially problematic code to anticipate everything that could go wrong with it, and learn other error-handling tips.

33 | Understanding the Document Object Model

Watch Bob examine the web browser environment and how it creates an object graph of nodes that represent elements, their attributes, and text, plus how to properly attach your code to an HTML page.

34 | Working with DOM Nodes

Continuing from the previous video, Bob demonstrates a slightly more compelling example that helps us understand how to manipulate, create, and delete element nodes and attribute nodes.

35 | Course Conclusion

In this final video, Bob briefly adds some closing comments and well wishes. You can also optionally complete a survey to provide insight into how Microsoft can improve this course.

Thanks for watching

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Functional Programming for JavaScript Developers

Functional Programming for JavaScript Developers

Functional Programming for JavaScript Developers. Learn Functional Programming and how it enables developers to move from imperative to declarative programming. Solidify your knowledge of functional JavaScript programming, including objects, arrays, and prototypes. Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript. Learning how to build and manage asynchronous functional programs is perhaps the most important part of becoming an effective JavaScript programmer.

Functional Programming for JavaScript Developers

Learn functional programming and how it enables developers to move from imperative to declarative programming

Improve your code with functional patterns like pure functions, compose & map/reduce/filter...plus advanced concepts like fusion, transducing and monads!

Solidify your knowledge of functional JavaScript programming, including objects, arrays, and prototypes

Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript. Go beyond the fundamentals of asynchronous JavaScript and use features and techniques that will help you reduce code and create smarter applications.

Learning how to build and manage asynchronous functional programs is perhaps the most important part of becoming an effective JavaScript programmer.

What you'll learn

  • On the surface, this course is designed for beginning and intermediate JS developers who want to learn the fundamentals in order to understand and use functional programming in both ES5 and ES6. However, this course is also perfect for people preparing to enter into competitive JavaScript bootcamps

Programming a Javascript Simon Game Tutorial

Programming a Javascript Simon Game Tutorial

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

For those who don't know, I'm a full stack web developer who has been in the industry for over 5 years now. There is a lot of things I have learned along the way and I'd like to share that knowledge with anyone wanting to learn!

like this video if you found it useful and would like to see more videos of the same content.

subscribe to my channel if you are trying to improve your abilities as a web developer, software engineer, or even if you are just learning to code.

Don't forget to turn on those bell notifications!