Marco Marco - 1 year ago 70
Javascript Question

jQuery one function

How to make a function jQuery one() on $(document).ready, I know the syntax for click events, and selectors, but I don't know how to make a function that would basically be run only on document ready, and only once, with switch statements in it?

Answer Source

By default the function will only be run once unless there are event listeners that call it more than once.

Rayon's answer is not the best. Put the function once() inside $(document).ready function so it won't pollute the global namespace. It also ensures a faster resolve of the function name because of JavaScript's scope chains.

Put it outside if it's a reusable component so you could easily move it in a separate file and call from different contexts. This would apply if you are developing a library or a big application.

$(document).ready(function() {
	function once() {
  	alert("See, this happens only once");
<script   src=""   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>