No Scrolling on Mobile
copy document.addEventListener ( 'touchmove' , e => e.preventDefault ( ) , { passive: false } ) ; document.body .innerHTML = 'Hi, no page scrolling here...' ;
It’s common to want to prevent page scrolling on mobile. Here is an easy way to do it.
Quick SVG
copy const el = document.body .appendChild ( document.createElement ( 'div' ) ) ; el.innerHTML = `< svg style= 'overlow:visible' > < circle cx= "100" cy= "20" r= "20" fill= "red" /> < rect x= "100" y= "60" width= "20" height= "20" fill= "blue" /> </ svg> `;
Try it out…
Defining SVG like this in a template string is a fast and powerful way to start doing SVG that is controlled or generated by JavaScript. Here is another example:
copy const scribble = document.body .appendChild ( document.createElement ( 'div' ) ) ; const d = ( iter = 30 ) => { // make sure the iter is odd if ( iter % 2 == 0 ) iter += 1 ; // random cubic beziér let path = 'M ' ; for ( let i = 0 ; i < iter; i++ ) { const cmd = i == 1 ? 'C ' : ' ' path += cmd + Math .random ( ) * 200 + ' ' + Math .random ( ) * 200 ; } return path + 'z' ; } scribble.innerHTML = `< svg style= 'overlow:visible' viewBox= "0 0 200 200" > < path d= "${d()}" stroke= "#295896" stroke- width= "3" fill= "#ccc" fill- rule= "even-odd" vector- effect= "non-scaling-stroke" /> </ svg> < style> svg, div, body, html { overflow: visible; height: 100 %; width: 100 %; margin: 0 ; padding: 0 ; } </ style> `;
Try it out…
You’ll notice a somewhat hacky style tag as well… this is used to quickly fill the page with the SVG.
Print a Tabula Recta (codegolf)
copy const tabulaRecta = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .replace ( /./g , "$&$'$`\n " ) ; const pre = document.createElement ( 'pre' ) ; document.body .appendChild ( pre) ; pre.innerHTML = tabulaRecta; // technique comes from https://codegolf.stackexchange.com/a/87035/63485
Try it out…
This snippet comes from the
the codegolf stackexchange . A little while back a challenge for printing a tabula recta popped up along with a very nice answer from user Neil . Take a look at the answer here .
Shuffle an Array
copy const nums = [ 1 , 10 , 20 , 30 , 50 , 88 ] ; nums.sort ( ( ) => Math .random ( ) - 0.5 ) ; console.log ( nums) ;
Try it out…
Common way to shuffle the values in an array.
Convert an Image to dataUri
copy function toDataUri( img, scalar = 1 ) { const canvas = document.createElement ( 'canvas' ) ; canvas.width = img.width * scalar; canvas.height = img.height * scalar; canvas.getContext ( '2d' ) .drawImage ( img, 0 , 0 , canvas.width , canvas.height ) ; return canvas.toDataURL ( 'image/png' ) ; } const img = new Image( ) ; img.crossOrigin = 'Anonymous' ; img.addEventListener ( 'load' , ( ) => { const thumb = new Image( ) ; // use the data URI as the source thumb.src = toDataUri( img, .3) ; document.body .appendChild ( thumb) ; } ) ; img.src = 'https://zevanrosser.com/fotoda/slide-shot-9.jpg' ;
Try it out…
Load an image and convert it to a data URI.