How to Execute Event Only Once using jQuery

How to Execute Event Only Once using jQuery

In this article, I am going to discuss How to Execute Event Only Once using jQuery with Examples. In our previous two articles, we have discussed Event Delegation using the jQuery Live function. At the end of this article, you will understand how to execute the jQuery Events only once using different approaches.

How to Execute jQuery Event Only Once?

We know that when we attach an event handler to an element using the jQuery on method that event is going to occur unlimited times whenever we execute that event. But what if we have to execute that event handler only once? In this article, we will discuss how to execute the event of an element only once. Let us understand this with an example.

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      body {
        font-family: Arial, Helvetica, sans-serif;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
      }
      #btn {
        background-color: #1c4450;
        border: none;
        outline: none;
        color: white;
        padding: 20px 35px;
        margin: 20px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
        text-transform: uppercase;
      }
      #btn:hover {
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
          0 17px 50px 0 rgba(0, 0, 0, 0.19);
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
    </style>
  </head>
  <body>
    <h1>How to Execute Event Only Once in jQuery</h1>
    <div class="container">
      <input id="btn" type="button" value="click me to see the changes" />
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $("#btn").on("click", function () {
          alert("You clicked this button");
        });
      });
    </script>
  </body>
</html>

Now run the above code and every time you click on the button, you will get the JavaScript alert as shown in the below image.

How to Execute Event Only Once using jQuery with Examples

But we don’t want that. We want that we should get the alert only once. If you want to execute the click event handler only once, then you will have to explicitly remove the click event handler. The following script removes the click event handler using the jQuery off() function after the alert is displayed. Just modify the script section of the previous example as follows.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
  $(document).ready(function () {
    $("#btn").on("click", function () {
      alert("You clicked this button");
      $(this).off("click");
    });
  });
</script>

Now when you click on the button for the first time, then you will get the alert as shown in the below image. But from the second time onwards when you click on the button, you will not get the alert.

How to Execute Event Only Once using jQuery

Now our desired functionality is achieved. Notice that the alert is displaying only once. The jQuery one() function does exactly the same thing. The click event is raised only once. On the first click, a JavaScript alert is displayed, but on subsequent clicks, nothing happens. To prove this, modify the script section of the previous example as follows.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
  $(document).ready(function () {
    $("#btn").one("click", function () {
      alert("You clicked this button");
    });
  });
</script>

With the above changes in place, now the JavaScript alert is displayed only once i.e. for the first time.

jQuery one() method

The one() method attaches one or more event handlers for the selected elements and specifies a function to run when the event occurs. When using the one() method, the event handler function is only run Once for each element.

Syntax: $(selector).one(event, data, function)

Parameters:
  1. event: Required. Specifies one or more events to attach to the elements. Multiple event values are separated by space. Must be a valid event.
  2. data: Optional. Specifies additional data to pass along to the function.
  3. function: Required. Specifies the function to run when the event occurs.

The syntax and type of usage of one() method is exactly the same as the on() method but in one() method the event handler executes only once. Let’s understand the one() method more clearly with another example.

Example: jQuery one() method

The following example binds 3 events (mouseover, mouse out, click) using the jQuery on() function.

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      body {
        font-family: Arial, Helvetica, sans-serif;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        transition: 0.5s;
      }
      #btn {
        background-color: #1c4450;
        border: none;
        outline: none;
        color: white;
        padding: 20px 35px;
        margin: 20px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
        text-transform: uppercase;
      }
      #btn:hover {
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
          0 17px 50px 0 rgba(0, 0, 0, 0.19);
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
    </style>
  </head>
  <body>
    <h1>How to Execute Event Only Once in jQuery</h1>
    <div class="container">
      <input id="btn" type="button" value="click me to see the changes" />
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $("#btn").on({
          mouseover: function () {
            $("body").css("background-color", "#a3a3a3");
          },
          mouseout: function () {
            $("body").css("background-color", "white");
          },
          click: function () {
            alert("Hello from jQuery");
          },
        });
      });
    </script>
  </body>
</html>

Notice in the above example, when you hover on the button the background color changes as shown in the below image.

jQuery one() method

Now put your mouse cursor out of the button and it will back to normal i.e. the background color removed as shown in the below image.

jQuery one() method with Examples

Now click on the button and you will get the alert as shown in the below image along with the background color.

one() method Examples in jQuery

The changes are happening every time when we execute an event on the button. If we want all these 3 events to execute only once, then we have to explicitly remove each event after the first execution using the jQuery off() method. To do so, modify the script section of the same example as follows.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
  $(document).ready(function () {
    $("#btn").on({
      mouseover: function () {
        $("body").css("background-color", "#a3a3a3");
        $(this).off("mouseover");
      },
      mouseout: function () {
        $("body").css("background-color", "white");
        $(this).off("mouseout");
      },
      click: function () {
        alert("Hello from jQuery");
        $(this).off("click");
      },
    });
  });
</script>

With the above changes in place, now, the events will execute only once. But in this case, we are explicitly removing each event after the first execution. We can use the jQuery one() method here. Let’s see how? Modify the Script section as shown below.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
  $(document).ready(function () {
    $("#btn").one({
      mouseover: function () {
        $("body").css("background-color", "#a3a3a3");
      },
      mouseout: function () {
        $("body").css("background-color", "white");
      },
      click: function () {
        alert("Hello from jQuery");
      },
    });
  });
</script>

Here we are using the jQuery one() method. Now this will produce exactly the same result i.e. the events will execute only once.

Example:

The jQuery one() function executes the handler at most once per element per event type. In the following example, click, mouseover, and mouse ount events are executed at most once for each button element.

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      body {
        font-family: Arial, Helvetica, sans-serif;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        transition: 0.5s;
      }
      .btn {
        background-color: #1c4450;
        border: none;
        outline: none;
        color: white;
        padding: 20px 35px;
        margin: 20px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
        text-transform: uppercase;
      }
      .btn:hover {
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
          0 17px 50px 0 rgba(0, 0, 0, 0.19);
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
    </style>
  </head>
  <body>
    <h1>How to Execute Event Only Once in jQuery</h1>
    <div class="container">
      <input class="btn" type="button" value="I am 1st Button" />
      <input class="btn" type="button" value="I am 2nd Button" />
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".btn").one({
          mouseover: function () {
            $("body").css("background-color", "#a3a3a3");
          },
          mouseout: function () {
            $("body").css("background-color", "white");
          },
          click: function () {
            alert("Hello from jQuery");
          },
        });
      });
    </script>
  </body>
</html>

In the above example, we are having two buttons so we are using the class selector here. And we have to execute the events once for each button. Hover on the 1st button and you will get the following output.

Execute Event Only Once in jQuery

Hover on the 2nd button and you will get the following output.

jQuery Execute Event Only Once

Now click on the 1st button and you will get the following output.

How to Execute jQuery Event Only Once

Now click on the 2nd button and you will get the below output.

How to Execute Event Only Once using jQuery with Examples

In the next article, I am going to discuss jQuery Prevent Default with Examples. Here, in this article, I try to explain How to Execute jQuery Event Only Once with Examples and I hope you enjoy this How to Execute jQuery Event Only Once article.

Leave a Reply

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