JavaScript Snippets

This page contains some code snippets in JavaScript. Use the input at the bottom of the page to test some code.

// Public domain functions by Ron Spain in 2019. Updates at http://ronspain.nfshost.com // shorthand for document.getElementById function get(s){return typeof s!="string"?s:document.getElementById(s)} // puts string b into element a function put(a,b){var e=get(a);if("innerHTML" in e)e.innerHTML=b;else e.value=b} // returns non-negative integer less than n function rnd(n){return Math.floor(Math.random()*n)} // replaceAll method for strings String.prototype.replaceAll=function(a,b){return this.split(a).join(b)}; // Add style rule(s) to page function css(s){ var e=document.createElement("style"); e.innerHTML=s; document.head.appendChild(e); } // moves element to coordinates if position is absolute function mv(e,x,y){ e=get(e).style; e.left=x+"px"; e.top=y+"px"; } // creates ltrim method for strings to trim whitespace from left side String.prototype.ltrim=function(){return this.replace(/^\s+/,"")}; // creates rtrim method for strings to trim whitespace from right side String.prototype.rtrim=function(){return this.replace(/\s+$/,"")}; // creates trim method for strings to trim whitespace on left and right side String.prototype.trim=function(){return this.ltrim().rtrim()}; // better than % modulus for keeping number within range function mod(a,b){return a-Math.floor(a/b)*b} // say something and remove it after a few seconds function say(s){ if(typeof msn!="number")msn=0; var e=document.createElement("div"); e.innerHTML=s; e.id="say"+msn; e.className="say"; document.body.appendChild(e); setTimeout(unsay,4000,msn); ++msn; } // used by the say function to remove text function unsay(n){get("say"+n).remove()} // add css needed by say css(".say{position:fixed;left:1%;top:1%;border-radius:8px;background-color:#000;color:#fff;padding:3px}"); //THE END

©2019 Ron Spain