How to make an event calls only once in JQuery
Today we will learn how we will learn how we can make an event to be fired only once in JQuery. This is a simple demo of JQuery .one() function. You may have gone through this situation in your development life. I hope you will like this.
Background
While I was doing some tasks, I wanted to make a click event which is to be fired only once for a user when the user is logged in. I used the JQuery .one function to do the requirement. So I thought of sharing you that.
Using the code
AS you all know we can handle so many events in client side by using JQuery. Hereby I am sharing you one of those event which will definitely help you one day in your application.
To start with load the JQuery reference. I am using Google CDN here.
[js]
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
[/js]
Now we will create a ‘p’ tag.
[html]
<p>Click Me</p>
[/html]
What next? Style that ‘p’ tag?
[css]
p {
color: red;
width: auto;
height: 50px;
margin: 250px;
border: 1px solid #ccc;
padding: 25px;
text-align: center;
}
[/css]
Now it is time to start our JQuery coding. For that we are going to create a document ready event and a click event.
[js]
<script>
$(document).ready(function(){
$("p").one( "click", function() {
$(this ).text("You clicked me!. Now you can’t do anything!!!!");
});
});
</script>
[/js]
So what does this .one() function does is, it will make sure that element’s click event is fired only once.
Complete Code
[html]
<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>
[/html]
Now we will see the output.
Output
Conclusion
I hope you will like this article. Please share me your valuable thoughts and comments. Your feedback is always welcomed.
Thanks in advance. Happy coding!
Kindest Regards
Sibeesh Venu