jQuery Plugin To Run A Function Only Once - Once.js
| File Size: | 16.7 KB |
|---|---|
| Views Total: | 3679 |
| Last Update: | |
| Publish Date: | |
| Official Website: | Go to website |
| License: | MIT |
Once.js is a small jQuery extension which allows you to execute a function only once on your DOM element.
How it works:
checkId(): Ensures that the given ID is valid, returning 'once' if one is not given.once(): Filters elements that have yet to be processed by the given data ID.removeOnce(): Removes the once data from elements, based on the given ID.findOnce: Filters elements that have already been processed once.
How to use it:
1. jQuery Once has a dependency on jQuery, so we wrap the code with a UMD pattern in order to allow loading jQuery and jQuery Once through a module definition like CommonJS, AMD, or through a global object.
<script src="//code.jquery.com/jquery.min.js"></script> <script src="jquery.once.js"></script>
2. The following will change the color of each paragraph to red, just once for the 'changecolor' key.
$('p').once('changecolor').css('color', 'red');
3. The .once() function will return a set of elements that yet to have the once ID associated with them. You can return to the original collection set by using .end().
$('p')
.once('changecolorblue')
.css('color', 'blue')
.end()
.css('color', 'red');
4. To execute a function on the once set, you can use jQuery's each().
$('.element').once().each(function () {
// Since there is no once ID provided here, the key will be 'once'.
});
5. The following will remove once data with the changecolor ID. The result set is the elements that had their once data removed.
$('p').removeOnce('changecolor').css('color', '');
6. Any jQuery function can be performed on the result set.
$('.element').removeOnce().each(function () {
// Remove the element behavior.
});
7. The following will find all elements that have been changecolor'ed once.
$('p').findOnce('changecolor').each(function () {
// This function is called for all elements that has already once'd.
});
8. Find all elements that have been acted on with the default 'once' key.
$('p').findOnce().each(function () {
// This function is called for all elements that have been acted on with
// a 'once' action.
});
Changelog:
v2.2.3 (2019-05-15)
- Fix CommonJS factory when export element is present
v2.2.2 (2019-05-09)
- Update dependencies
v2.2.1 (2018-03-30)
- Updated dependencies
This awesome jQuery plugin is developed by RobLoach. For more Advanced Usages, please check the demo page or visit the official website.











