Functii personalizate JavaScript
Inainte de a folosi urmatoarele functii, este necesar sa cunoasteti destul de bine ECMAScript/JavaScript. La fel ca majoritatea programatorilor, numele functiilor si al parametriilor vor fi in limba engleza.
getCSSPropertyValue
Asa cum ii spune si numele, aceasta functie va returna valoarea proprietatii CSS pe care o eticheta HTML o are.
function getCSSPropertyValue(tagObj, property){ let obj = typeof tagObj == `string` ? document.querySelector(tagObj) : tagObj; return obj && property ? window.getComputedStyle(obj).getPropertyValue(property) : null; } getCSSPropertyValue("#idName", "propertyName"); // sau getCSSPropertyValue(".className", "propertyName");
scrollTagIntoView
Aceasta functie va forta browserul sa afiseze respectiva eticheta HTML in centrul ecranului.
function scrollTagIntoView(objTagHTML){ objTagHTML.scrollIntoView({ behavior: `smooth`, block: `center`, inline: `center` }); }
noFrame
Urmatoarea functie va trimite browserul catre pagina de Google sau oricare va doriti daca respectiva pagina unde aceasta functie este apelata va fi afisata printr-o eticheta HTML iframe.
function noFrame(){ if(window.self !== window.top){ window.location = `//google.com`; } document.onkeydown = (e)=>{ if(e.ctrlKey && e.keyCode == 83){ e.preventDefault(); } }; }
getTextSelected
Asa cum ii spune si numele, aceasta functie va returna textul ce este selectat din fereastra browserului. In caz de esec, va returna valoarea booleana fals.
function getTextSelected(){ if(window.getSelection){ return window.getSelection().toString(); } else if(document.getSelection){ return document.getSelection().toString(); } else{ let selection = document.selection && document.selection.createRange(); if(selection.text){ return selection.text; } return false; } }
dragOnWindow
Aceasta functie va lasa posibilitatea utilizatorului sa miste pe axele X si Y o eticheta HTML in fereastra browserului. Functia are doi parametrii, ambii reprezinta fie un sir de caractere cu selector CSS fie numele unei variabile ce selecteaza cate o eticheta HTML. Primul este eticheta de care se va "trage", iar al doilea este eticheta de "mutat". Daca eticheta de "mutat" lipseste, aceasta va fi inlocuita de cea de care se "trage".
function dragOnWindow(targetToDrag, targetToMove){ let objTargetToDrag = typeof targetToDrag == `string` ? document.querySelector(targetToDrag) : targetToDrag, objTargetToMove = typeof targetToMove == `string` ? document.querySelector(targetToMove) : targetToMove, offset = [0,0], bool = false, setBoolToFalse = () => bool = false, options = {passive: true}; if(!objTargetToMove){ objTargetToMove = objTargetToDrag; } if(objTargetToDrag && objTargetToMove){ objTargetToDrag.onmousedown = (e)=>{ e.stopPropagation(); bool = true; offset = [ objTargetToMove.offsetLeft - e.clientX, objTargetToMove.offsetTop - e.clientY ]; }; objTargetToDrag.onmouseup = setBoolToFalse; objTargetToDrag.onmouseleave = setBoolToFalse; objTargetToDrag.onmousemove = (e)=>{ e.preventDefault(); e.stopPropagation(); if(bool){ objTargetToMove.style.left = `${e.clientX + offset[0]}px`; objTargetToMove.style.top = `${e.clientY + offset[1]}px`; objTargetToMove.style.position = "fixed"; } }; objTargetToDrag.addEventListener("touchstart", (e)=>{ bool = true; offset = [ objTargetToMove.offsetLeft - e.touches[0].clientX, objTargetToMove.offsetTop - e.touches[0].clientY ]; }, options); objTargetToDrag.addEventListener("touchend", ()=>{ bool = false; }, options); objTargetToDrag.ontouchmove = (e)=>{ e.preventDefault(); e.stopPropagation(); if(bool){ objTargetToMove.style.left = `${e.touches[0].clientX + offset[0]}px`; objTargetToMove.style.top = `${e.touches[0].clientY + offset[1]}px`; objTargetToMove.style.position = "fixed"; } }; } }
dontGoYet
O functie foarte utila in aplicatii web prin care ii spunem utilizatorului ca daca reincarca pagina sau o inchide, setarile/modificarile in aplicatia web nu vor putea fi recuperate.
function dontGoYet(){ window.onbeforeunload = (_) => { const e = _ || window.event; e.preventDefault(); if(e){ e.returnValue = ''; } return ''; }; }
randPass
O functie ce va returna un sir de caractere (implicit 8) aleatoriu alese dintr-o variabila interna.
function randPass(n = 8){ let data = [ `a`,`b`,`c`,`d`,`e`,`f`,`g`,`h`,`i`,`j`,`k`,`l`,`m`, `n`,`o`,`p`,`q`,`r`,`s`,`t`,`u`,`v`,`w`,`x`,`y`,`z`, `A`,`B`,`C`,`D`,`E`,`F`,`G`,`H`,`I`,`J`,`K`,`L`,`M`, `N`,`O`,`P`,`Q`,`R`,`S`,`T`,`U`,`V`,`W`,`X`,`Y`,`Z`, `0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`, `~`,`?`,`!`,`@`,`#`,`$`,`%`,`^`,`&`,`*`,`(`, `)`,`[`,`]`,`{`,`}`,`|`,`_`,`=`,`+`,`;`,`:` ], str = ``; for(let i = 0; i < n; ++i){ str += data[Math.floor(Math.random() * data.length)]; } return str; }
shuffleTxt
Aceasta functie va "amesteca" caracterele text intre ele.
function shuffleTxt(txt){ let ret = ''; txt = txt.split(''); while(txt.length > 0){ ret += txt.splice(txt.length * Math.random() << 0, 1); } return ret; }
swipeOnElement
O functie foarte importanta daca esti creator de jocuri JavaScript. O astfel de functie este utilizata in jocul 2048 pentru a afla daca utilizatorul a glisat cu degetul in sus/jos/stanga sau dreapta. Functia are cinci parametri. Primul reprezinta eticheta HTML tinta pe care urmeaza (sau urmeaza) sa se gliseze cu degetul iar urmatorii patru parametri reprezinta numele functiilor ce vor fi apelate daca se gliseaza catre stanga, dreapta, in sus sau in jos in aceasta ordine.
function swipeOnElement(target, funSwipeLeft = ()=>{}, funSwipeRight = ()=>{}, funSwipeUp = ()=>{}, funSwipeDown = ()=>{}){ let obj = typeof target == `string` ? document.querySelector(target) : target, offset = 1, xDown, yDown, options = { passive: true }, getTouch = e=>e.changedTouches[0], funTouchStart = async (e)=>{ e.stopPropagation(); let firstTouch = getTouch(e); xDown = firstTouch.clientX; yDown = firstTouch.clientY; }, funTouchEnd = async (e)=>{ e.stopPropagation(); if(!xDown || !yDown){ return; } let {clientX: xUp, clientY: yUp} = getTouch(e), xDiff = xDown - xUp, yDiff = yDown - yUp, xDiffAbs = Math.abs(xDown - xUp), yDiffAbs = Math.abs(yDown - yUp); if(Math.max(xDiffAbs, yDiffAbs) < offset){ return; } if(xDiffAbs > yDiffAbs){ xDiff > 0 ? funSwipeLeft() : funSwipeRight(); } else{ yDiff > 0 ? funSwipeUp() : funSwipeDown(); } }; obj.addEventListener(`touchstart`, funTouchStart, options); obj.addEventListener(`touchend`, funTouchEnd, options); }
addPixelImageEffectOverImage
Aceasta functie creaza o eticheta HTML canvas cu grafica unei imaginisub forma de eticheta HTML data ca parametru. Noutatea este ca imaginea apare la inceput pixelata si intr-un interval scurt devine tot mai clara, rezolutia devenind din ce in ce mai mare. Efectul este foarte interesant, incearca aceasta functie.
function addPixelImageEffectOverImage(targetIMG){ let obj = typeof targetIMG == `string` ? document.querySelector(targetIMG) : targetIMG; if(obj.tagName && obj.tagName == `IMG`){ let offset = obj.getBoundingClientRect(), image = obj, styleWidth = offset.width, styleHeight = offset.height, width = offset.width, height = offset.height, scaledWidth, scaledHeight, percent = 0.01, canvas = document.createElement(`canvas`), ctx = canvas.getContext(`2d`), init = ()=>{ width = width * window.devicePixelRatio; height = height * window.devicePixelRatio; applyCanvas(); draw(); }, applyCanvas = ()=>{ canvas.style.position = `fixed`; canvas.style.top = `${offset.top}px`; canvas.style.left = `${offset.left}px`; canvas.style.zIndex = 1e3; canvas.width = width; canvas.height = height; canvas.style.width = `${styleWidth}px`; canvas.style.height = `${styleHeight}px`; document.body.appendChild(canvas); scaledWidth = width * percent; scaledHeight = height * percent; ctx.imageSmoothingEnabled = false; }, draw = ()=>{ ctx.drawImage(image, 0, 0, scaledWidth, scaledHeight); ctx.drawImage(canvas, 0, 0, scaledWidth, scaledHeight, 0, 0, width, height); }, reveal = ()=>{ percent = percent < 0.1 ? percent += 0.002 : percent += 0.01; if(percent > 1){ percent = 1; } scaledWidth = width * percent; scaledHeight = height * percent; ctx.drawImage(image, 0, 0, scaledWidth, scaledHeight); ctx.drawImage(canvas, 0, 0, scaledWidth, scaledHeight, 0, 0, width, height); if(percent < 1){ requestAnimationFrame(reveal); } }, generatePixelImages = ()=>{ init(); reveal(); }, remove = ()=>{ canvas.remove(); }; if(styleWidth == 0 || styleHeight == 0){ return; } generatePixelImages(); canvas.onclick = remove; setTimeout(remove, 1000); } }
getPercentage
Aceasta functie returneaza procentul de date folosit (amount) din valoarea maxima (max).
function getPercentage(amount, max){ return !amount || !max ? null : ((amount / max) * 100).toPrecision(3); }
getFactorial
Aceasta functie nu ar trebui sa aiba nevoie de prezentare. Codul se explica singur.
function getFactorial(num){ let val = 1; for(let i = 2; i <= num; ++i){ val = val * i; } return val; }