Skip to content

Instantly share code, notes, and snippets.

@rocket111185
Last active February 27, 2024 16:28
Show Gist options
  • Save rocket111185/35e30ee48a1bfeffb4d34abc851f00bf to your computer and use it in GitHub Desktop.
Save rocket111185/35e30ee48a1bfeffb4d34abc851f00bf to your computer and use it in GitHub Desktop.
Function triggerOnceWhenElementExists. It creates jQuery listeners which will trigger the code on a specific event eventName once only if the element exists
function generateRandomIdentifier(length) {
const firstLetterCode = 97;
const numberOfLetters = 25;
const randomCharacter = function () {
const letterPosition = Math.round(numberOfLetters * Math.random());
return String.fromCharCode(firstLetterCode + letterPosition);
};
let identifier = '';
for (let i = 0; i < length; i += 1) {
identifier += randomCharacter();
}
return identifier;
}
function triggerOnceWhenElementExists(eventName, elementSelector, callback) {
// 12 letters should be enough in order not to create collision of
// coexisting custom events
const customEventName = generateRandomIdentifier(12);
const triggerHandler = function () {
if ($(elementSelector).length > 0) {
$(document).trigger(customEventName);
}
};
$(document).on(eventName, triggerHandler);
// Trigger only once
$(document).one(customEventName, function () {
callback();
// Unbind the existing listener, since it's not needed anymore
$(document).off(eventName, triggerHandler);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment