<div>
<input value='Hey There!' />
<input value='Tab or Click!' />
</div><br/>
<div>
Changed: <span id="changedPlaceholder"></span>
</div>
<div>
On: <span id="onPlaceholder"></span>
</div>
<div>
One: <span id="onePlaceholder"></span>
</div>
<div>
Once: <span id="oncePlaceholder"></span>
</div>
<div>
Only: <span id="onlyPlaceholder"></span>
</div>
<!-- Post Info -->
<div style='position:fixed;bottom:0;left:0;
background:lightgray;width:100%;'>
About this SO Question: <a href='http://stackoverflow.com/q/24589084/1366033'>jQuery's One - Fire once with multiple event types</a><br/>
<div>
JavaScript
$.fn.once = function (events, callback) {
//The handler is executed at most once per element for all event types.
return this.each(function () {
$(this).on(events, myCallback);
function myCallback(e) {
$(this).off(events, myCallback);
callback.call(this, e);
}
});
};
$.fn.only = function (events, callback) {
//The handler is executed at most once for all elements for all event types.
var $this = $(this).on(events, myCallback);
function myCallback(e) {
$this.off(events, myCallback);
callback.call(this, e);
}
return this
};
$('input').once('mouseup keyup', function(e){
console.log(e.type);
console.log(this);
});
var changed = false;
var on = one = once = only = 0
$(":input").on('change',function() {
changed = true;
on += 1;
setChangedText();
});
$(":input").one('change',function() {
changed = true;
one += 1;
setChangedText();
});
$(":input").once('change',function() {
changed = true;
once += 1;
setChangedText();
});
$(":input").only('change',function() {
changed = true;
only += 1;
setChangedText();
});
setChangedText();
function setChangedText() {
$("#changedPlaceholder").text(changed);
$("#onPlaceholder").text(on);
$("#onePlaceholder").text(one);
$("#oncePlaceholder").text(once);
$("#onlyPlaceholder").text(only);
}
// event logger
$("input").on("mousedown mouseup keydown keyup",
function(e) {
console.log(e.type + ' logged');
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.