Introduction
Today we will learn how to fire an event only once in jQuery. This is a simple demo of the jQuery one() function. I hope you will like it.
Please see to this article in my blog.
Background
While I was doing some tasks, I wanted to make a click event that is to be fired only once for a user when the user is logged in. I used the jQuery one function to do it, so I thought of sharing it with you all.
Using the code
As you all know we can handle many events in the client side using jQuery. Here I am sharing with you one of those events that will definitely help you one day in your application.
To start with loading the jQuery reference, I will use the Google CDN here:
- <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
Now we will create a "p" tag.
What next? Style that "p" tag?
- p {
- color: red;
- width: auto;
- height: 50px;
- margin: 250px;
- border: 1px solid #ccc;
- padding: 25px;
- text-align: center;
- }
Now it is time to start our jQuery coding. For that we will create a document ready event and a click event.
- <script>
- $(document).ready(function(){
- $("p").one( "click", function() {
- $(this ).text("You clicked me!. Now you can't do anything!!!!");
- });
- });
- </script>
So what this one() function does is it ensures that elements of the click event is fired only once.
Complete Code
- <html>
- <head>
- <title>JQuery one demo - Sibeesh Passion</title>
- <style>
- p {
- color: red;
- width: auto;
- height: 50px;
- margin: 250px;
- border: 1px solid #ccc;
- padding: 25px;
- text-align: center;
- }
- </style>
- <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
- </head>
- <body>
- <p>Click Me</p>
- <script>
- $(document).ready(function(){
- $("p").one( "click", function() {
- $(this ).text("You clicked me!. Now you can't do anything!!!!");
- });
- });
- </script>
- </body>
- </html>
Now we will see the output.
Output
ConclusionI hope you will like this article. Please share with me your valuable thoughts and comments. Your feedback is always welcome.
Thanks in advance. Happy coding!