Kawiesh

[NEW] JS Notes

Aug 7th, 2021 (edited)
1,549
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //-----------------------TRUTHY FALSY---------------------------
  2.  
  3. Conditional/Ternary operator
  4. Syntax=>  condition ? exprIfTrue : exprIfFalse
  5. Example=> (age>10) "old" ? "young"
  6.  
  7. If condition is true or truthy, do 1st expression else do 2nd expression
  8.  
  9. //---------------------
  10. Falsy: value that is considered false when encountered in a Boolean context
  11. 0, null, NaN, undefined, empty string: "  "
  12.  
  13. Truthy: anything but falsy
  14.  
  15. //----------------------
  16. Logical OR operator
  17. Syntax=> leftExpr || rightExpr
  18. Example=> let name= result || "Unknown";
  19.  
  20. If result is 0, null, NaN, undefined or an empty string: "  ", let name be "Unknown"
  21.  
  22. //----------------------
  23. Nullish coalescing operator
  24. Syntax=> leftExpr ?? rightExpr
  25. Example=> let name= result ?? "Unknown";
  26.  
  27. If result is null or undefined let name be "Unknown"
  28. Same as logical OR but if first operand is NaN, 0, or an empty string, it uses the value,
  29. rather than taking the value of the 2nd operand
  30.  
  31.  
  32. //-----------------------QUERYSELECTOR---------------------------
  33. How to select elements whose IDs contain a dot
  34. Dots are meant for classes so you need to escape them using backslash
  35. Example: <span id="my.span">hi</span>
  36.  
  37. CSS
  38. #my\.span{
  39. rules
  40. }
  41.  
  42. JavaScript
  43. document.querySelector("#my\\.span")
  44. Note: 2 backslashes because strings naturally consume backslashes
  45.  
  46.  
  47. //------------------------AJAX------------------------------
  48. function lawlz(a){
  49. if(a==200){ alert("yes");}
  50. if(a==404){ alert("error");}
  51. }
  52.  
  53. var xhr = new XMLHttpRequest();
  54. xhr.open('GET', location.href, true);
  55.  
  56.  
  57. xhr.onload = function () {
  58. if (xhr.readyState === xhr.DONE) {
  59. lawlz(xhr.status);
  60. }};
  61.  
  62. xhr.send(null);
  63.  
  64. //------------------------BATTERY------------------------------
  65. navigator.getBattery()
  66.   .then(function(battery) {
  67.     alert(battery.level*100+"%");
  68. });
  69.  
  70. //------------------------CLIPBOARD & SELECTION------------------------------
  71. navigator.clipboard.writeText();
  72.  
  73. //---------
  74. document.body.onclick= function(){
  75. let a= window.getSelection(),
  76.     b= document.createRange();
  77.     b.selectNodeContents(event.target);
  78.     a.removeAllRanges();
  79.     a.addRange(b);
  80. };
  81.  
  82.  
  83. let a= getSelection().toString();
  84. b= window.open();
  85. b.document.write(a);
  86.  
  87. //------------------------STYLESHEET------------------------------
  88. let a= document.querySelector("a"),
  89. b= getComputedStyle(a), // or (a,null) for pseudoelements
  90. c= "";
  91.  
  92. b.backgroundColor
  93. b.getPropertyValue("background-color")
  94.  
  95. //--------
  96. for (i= 0; i< b.length; i++) {
  97. bProp = b.item(i)
  98. c+= bProp+" = "+b.getPropertyValue(bProp)+"<br>";
  99. }
  100. document.body.append(c);
  101.  
  102. //------
  103. let x= document.styleSheets[0].cssRules[0].style,
  104. x.setProperty("background-color", "yellow","important");
  105. //last parameter is optional
  106.  
  107. //--------------------Element Outerhtml----------------------------
  108. document.body.onclick= function(){
  109. alert(event.target.parentNode.outerHTML);
  110. }
  111.  
  112.  
  113.  
  114. //--------------------Object Iteration------------------------------
  115. let urls= {
  116. "radio1":"url1",
  117. "radio2":"url2",
  118. "radio3":"url3",
  119. "radio4":"url4"
  120. };
  121.  
  122. for(let i in urls){
  123. if (urls.hasOwnProperty(i)){
  124. alert(i + ":" + urls[i]);
  125. }}
  126.  
  127. //------------
  128. for (let i of Object.keys(urls)) {
  129. alert(i + ":" + urls[i])
  130. }
  131.  
  132. //------------
  133. for (let [i, x] of Object.entries(urls)){
  134. alert(i+":"+x);
  135. }
  136.  
  137. //------------
  138. Object.entries(urls).forEach(
  139. ([i,x]) => alert(i+":"+x)
  140. )
  141.  
  142. //------------
  143. Object.keys(urls).forEach(
  144. i=> alert(i+":"+urls[i])
  145. );
  146.  
  147. //------------
  148. for (let i in urls) {
  149. if (!urls.hasOwnProperty(i)) {
  150. continue;
  151. }
  152. alert(i+":"+urls[i])
  153. }
  154.  
  155. //------------
  156. let keys = Object.keys(urls),
  157. length = keys.length,
  158. i= 0, prop, value;
  159. while (i < length) {
  160. prop = keys[i];
  161. value = urls[prop];
  162. i += 1;
  163. alert(prop+":"+value);
  164. }
  165.  
  166. //----
  167. let list= {
  168. };
  169.  
  170. let link= Object.keys(list),
  171.     tit= Object.values(list);
  172.  
  173. let b= [];
  174.  
  175. link.forEach((i,x)=>{
  176. b.push(`<span>${tit[x]}<br>
  177. <audio controls src="${i}"></audio>
  178. </span>`);
  179. });
  180.  
  181.  
  182.  
  183.  
  184. //--❌❌❌❌❌❌❌❌SORT OBJECT
  185.  
  186. function sortObject(obj,mode="keys",order="asc"){
  187. let result= Object.keys(obj);
  188. if(mode=="keys"){
  189. result= (order=="asc") ?
  190. result.sort((a,b)=>a>b ? 1:-1) :
  191. result.sort((a,b)=>a<b ? 1:-1);
  192. }
  193. else{
  194. result= (order=="asc") ?
  195. result.sort((a,b)=>obj[a]>obj[b] ? 1:-1) :
  196. result.sort((a,b)=>obj[a]<obj[b] ? 1:-1);
  197. }
  198.  
  199. result= result.reduce((a,b)=>{
  200. a[b]= obj[b];
  201. return a;
  202. },{});
  203.  
  204. return result;
  205. }
  206.  
  207.  
  208. //CALL THE FUNCTION
  209. let sorted= sortObject(obj,"values","asc");
  210. //❌❌❌❌
  211.  
  212.  
  213. //--------------------VIDEO INJECTION------------------------------
  214. let z= window.open('','blank');
  215. z.document.head.innerHTML=`
  216.  
  217. <title></title>
  218.  
  219. <style>
  220. body{
  221. background-color:black;
  222. }
  223. #vid{
  224. margin: 0 auto; display:block;
  225. border: 1px solid gray;
  226. }
  227. #txt{
  228. color:#0f3;
  229. text-align:center;
  230. font-family: arial;
  231. }
  232.  
  233. </style>`;
  234.  
  235. z.document.body.innerHTML=`
  236. <div id='txt'>
  237. Streaming over local network!
  238. </div>
  239. <video id= 'vid' controls autoplay>
  240. <source src='http://ik.nl/hey.mp4'>
  241. </video>`;
  242.  
  243. //--------------------OPEN WINDOW & WRITE------------------------------
  244. /*Use backticks or template literals for
  245. multi ine strings and  to insert variables within the strings*/
  246.  
  247. let a= window.open();
  248. let b= 'okay boomer';
  249. a.document.body.innerHTML=`
  250. <h3>hello<h3>
  251. <h2> ${b}<h2>`;
  252.  
  253. //-------------
  254. let a= window.open('','','',false);
  255.  
  256. a.document.head.innerHTML=`
  257. <title> okay </title>
  258. <style>
  259. body {
  260. text-align: center;
  261. border: 3px double green;
  262. color:red;
  263. }
  264. </style>`
  265.  
  266. a.document.body.innerHTML= 'hey';
  267.  
  268. //-------------
  269. let a= window.open('','','',false),
  270.     b= a.document.createElement('title'),
  271.     c= a.document.createTextNode('yes'),
  272.     d= a.document.createElement('style'),
  273.     e= a.document.createTextNode(`
  274.     body{color:red`);
  275.  
  276. a.document.body.innerHTML= 'hey';
  277. d.appendChild(e);
  278. b.appendChild(c);
  279. a.document.head.appendChild(b);
  280. a.document.head.appendChild(d);
  281.  
  282.  
  283.  
  284. //--------------------REGEX TEST------------------------------
  285. try{
  286. let a=`a
  287. b
  288. c`,
  289. b= a.split('\n'),
  290. c='20.',
  291. d=/\d+/,
  292. e= c.match(d);
  293.  
  294. for(let i=0, x=e; i<b.length; i++, x++){
  295. let D= c.replace(e,x);
  296. b[i]= D+b[i];
  297. alert(b[i]);
  298. }
  299. }
  300. catch(x){
  301. alert(x);
  302. }
  303.  
  304. //------------------------TYPEWRITER EFFECT------------------------------
  305. let a= document.querySelector("span");
  306. let c= document.querySelector("h1");
  307. let b= "Hello";
  308. let stopped = true;
  309. let stop= 8;
  310.  
  311.  
  312. let i=0;
  313. let r= setInterval(()=>{
  314. if(i==b.length){
  315. stopped = true;
  316. clearInterval(r);
  317. a.style.color="red";
  318. c.innerHTML= stopped;
  319. }
  320. if(i<b.length){
  321. a.innerHTML+= b[i];
  322. i++;
  323. }
  324. c.innerHTML= stop;
  325. stop++;
  326. },100);
  327.  
  328. r;
  329.  
  330.  
  331. //------------------------PAGE ERRORS------------------------------
  332. Error 401
  333. Sorry, you aren’t authorized to access this page.
  334.  
  335. Error 403
  336. Sorry, you aren’t authorized to access this page.
  337.  
  338. Error 400
  339. Oops, the request to the web server was somehow corrupted!
  340.  
  341. Error 404
  342. Sorry this page does not exist!
  343.  
  344. Error 500
  345. The web server encountered some form of internal error & was unable to handle the request properly.
  346.  
  347. //------------------------CHANGE VIEWPORT------------------------------
  348. let a= document.querySelector("meta[name='viewport']");
  349.  
  350. if (a){
  351. a.outerHTML=`<meta name="viewport" content="width=device-width, initial-scale=0.7">`;
  352. }
  353. else{
  354. let b= document.createElement("meta");
  355. b.name= "viewport";
  356. b.content= "width=device-width, initial-scale=0.7";
  357. document.head.append(b);
  358. }
  359.  
  360. //------------------------LEADING ZEROS------------------------------
  361. function pad(num, size) {
  362. let s= "000" + num;
  363. return s.substr(s.length-size);
  364. }
  365.  
  366. let a= "1";
  367.  
  368. alert(pad(a,3));
  369.  
  370. //------------------------CUSTOM CHECKBOX------------------------------
  371. <html>
  372. <head>
  373. <style>
  374. span{
  375. display: block;
  376. height: 12px; width: 12px;
  377. border: 1px solid black;
  378. }
  379.  
  380. span>svg{
  381. stroke: black; stroke-width: 2;
  382. max-height:100%; max-width:100%;
  383. }
  384. </style>
  385. </head>
  386. <body>
  387. <script>
  388.  
  389. let on= `<svg viewBox="0 0 24 24"><path d="M20 20L4 4m16 0L4 20"/></svg>`;
  390. let checkbox= document.queryselector("span");
  391. checkbox.innerHTML= "";
  392.  
  393. //----------
  394. let checked= false;
  395. checkbox.onclick=()=>{
  396. if(checked){
  397. checkbox.innerHTML= "";
  398. checked= false;
  399. }
  400. else{
  401. checkbox.innerHTML= on;
  402. checked= true;
  403. }
  404. }
  405.  
  406. //-------------
  407. checkbox.onclick= function(){
  408. this.classList.toggle("checked");
  409. if(this.className=="checked"){ //this.classList.contains("checked");
  410. this.innerHTML= "";
  411. this.style.background= "none";
  412. }
  413. else{
  414. this.innerHTML= on;
  415. this.style.background= "white";
  416. }
  417. };
  418. </script>
  419. </body>
  420. </html>
  421.  
  422. //------------------------DROPDOWN SELECT ELEMENT------------------------------
  423. <select id="singular">
  424. <optgroup label= "Choose one:">
  425. <option value="a">Value a</option>
  426. <option value="a">Value b</option>
  427. <option value="a">Value c</option>
  428. </optgroup>        
  429. </select>
  430.  
  431. <select id="multiple" multiple>
  432. <optgroup label= "Options:">
  433. <option value="a">Value a</option>
  434. <option value="a">Value b</option>
  435. <option value="a">Value c</option>
  436. </optgroup>        
  437. </select>
  438.  
  439. let sing= document.querySelector("#singular");
  440. let singval= sing.options[sing.selectedIndex].value;
  441.  
  442. let mult= document.querySelector("#multiple");
  443. let multval=
  444. Array.from(selectAll("option:checked",mult),e=>e.value);
  445.  
  446. let sort= false, dupes= false;
  447. optionval.forEach(i=>{
  448. if (i=="a") sort= true;
  449. if (i=="a") dupes= true;           
  450. });
  451. //-------
  452. let select= (x,y=document)=> y.querySelector(x),
  453. selectAll= (x,y=document)=> y.querySelectorAll(x);
  454.  
  455. let sing= selectAll("option", select("#singular"));
  456. let mult= selectAll("option", select("#singular"));
  457.  
  458. if(sing[0].selected) bla bla
  459. if(mult[3].selected) bla bla
  460.  
  461.  
  462. //------------------------SORTING ARRAYS------------------------------
  463. function sortaz(str) {
  464. return str.split("\n").sort((a, b) => a.localeCompare(b)).join("\n");
  465. }
  466.  
  467. output.value= sortaz(output.value);
  468.  
  469. //------------------------Removing Duplicates------------------------------
  470. function remdupes(str){
  471. let a= str.split("\n"); // or given array
  472. let b= new Set(a);
  473. return [...b].join("\n");
  474. }
  475.  
  476. //--------
  477. let oldArray= ["a",1,2,2,3,1];
  478. let uniqueArray= [...new Set(oldarray)]; //["a",1,2,3]
  479.  
  480.  
  481. //------------------------Bookmarklet------------------------------
  482. let code= javascript code;
  483. let url= url to javascript code;
  484.  
  485. //Local bookmarklet
  486. javascript:(function(){${encodeURIComponent(code)}})();
  487.  
  488. //Remote bookmarklet
  489. javascript:var%20q=document.createElement('script');q.src='${url}';document.body.appendChild(q);void%200;
  490.  
  491. //------------------ARRAY MANIPULATION--------------------------
  492. let a= 'hey.this.is.a.test.lol-bye',
  493.     b= a.split('.'),  //creates array w. 6 elements
  494.     c= b[b.length-1], //element with index 5 (6-1)
  495.     d= b[b.length-4], //element with index 2 (6-4)
  496.     e= b.join('~');   //join elements w. seperator
  497.  
  498. alert(d);
  499.  
  500. /*------------
  501. To grab an element in an array:
  502. -Number the elements from right to left starting with 1
  503. -Then substract desired element('s number) from array.length
  504. -This will result in the index of the desired element
  505.  
  506. Example:
  507. let x= [hey,how,are,you];
  508. To get 'how' do x[x.length - number(how)] => x[4-3]--> x[1]
  509.  
  510. ---------------*/
  511. let oldone= [];
  512.  
  513. let thisone= oldone.slice(1,5);
  514. //creates new array containing (4) elements from 'oldone' w. index 1,2,3,4
  515.  
  516. let thisone= oldone.splice(1,5);
  517. //creates new array containing (5) elements from 'oldone' w. index 1,2,3,4,5          
  518.            
  519. /*-----
  520. Splice returns elements from given range [start, end]
  521. Slice  returns elements from given ranhe [start, end)
  522. ** math notation  [ means included, ( means excluded**
  523. Splice modifies array, Slice doesn't modify the array.
  524. If no end value is entered, end = ∞
  525. (will stop at array.length, til last element in array)
  526.  
  527. Use array.join('❌') to join arrays.
  528. Default separator in arrays are commas
  529. ----------*/
  530.  
  531. let oldone= ['hey', 'how', 'are', 'you'];
  532. let newone= old.slice(0,3);
  533. newone= newone.join('×'); //'hey×how×are'
  534.  
  535.  
  536.  
  537. /*------------------DIGITS IN URLS--------------------------
  538. Observation:
  539. It seems like numbers/digits in URLs are viewed as strings and not numbers.
  540. So while using the strict equality operator, the numbers should be placed between quotes.
  541. Or the loose equality operator can be used which will automatically do the conversion.
  542.  
  543. Example:
  544. if (d===1) will never result in true
  545. if (d==='1') can result in true
  546. if (d==1) can also result in true.
  547. The loose equality operator converted 1 to a string
  548.  
  549. assuming d is part of an URL------ */
  550.  
  551.  
  552. //------------------TIME AND DATE--------------------------
  553. //----Time
  554. function time(x="hm"){
  555. let a= new Date().toLocaleTimeString('en-US');
  556. let b= a.split(":");
  557. let h= b[0], m= b[1], s= b[2];
  558. if(x=="hm") return (h+":"+m+ s.match(/\D+/g));
  559. if(x=="hms") return (h+":"+m+":"+s);
  560. };
  561.  
  562. element.innerHTML= time;
  563.  
  564. //----Date
  565. function datez(x="en-US"){
  566. let a= new Date();
  567. let b= {
  568. weekday: 'long',
  569. year: 'numeric',
  570. month: 'long',
  571. day: 'numeric'
  572. };
  573.  
  574. return a.toLocaleDateString(x, b);
  575. };
  576.  
  577. let lol1= datez();
  578. let lol2= datez("nl-NL");
  579.  
  580. alert(lol1);
  581.  
  582.  
  583. //------------------JSON--------------------------
  584. JSON.stringify(obj);
  585. JSON.parse(obj);
  586.  
  587.  
  588.  
  589. //------------------Fetch & Api--------------------------
  590.  
  591. response.json() parses the response body text as JSON.
  592. This JSON is then used as input and parsed, producing an js *object*
  593. *
  594.  
  595. let url= "https://type.fit/api/quotes";
  596.  
  597. fetch(url)
  598. .then(response => response.json())
  599. .then(data => {
  600. let a= Math.floor(Math.random() * data.length);
  601. alert(data[a].text+ "~" + data[a].author);
  602. })
  603.  
  604.  
  605. //returns array with 1643 objects
  606. //each object contains text ans author peoperty and value
  607.  
  608.  
  609. //------------------LIST LINKS-------------------------
  610. let create= (x)=> document.createElement(x),
  611. select= (x,y=document)=> y.querySelector(x),
  612. selectAll= (x,y=document)=> y.querySelectorAll(x);
  613.  
  614. let a= selectAll("a"),
  615. b= window.open(),
  616. c= create("textarea");
  617. c.style.cssText= `width: 100vw;
  618. min-height: 100vh;
  619. padding:5px;
  620. border:2px double blue;`;
  621.  
  622. b.document.body.append(c);
  623.  
  624. let ok= [...a].map(i=>{
  625. return i.textContent+" : "+ i.href;
  626. });
  627.  
  628. c.value= ok.join("\n");
  629.  
  630.  
  631.  
  632. //------------------FIND ELEMENTs-------------------------
  633. function findElements(elem, selector, filter) {
  634. let siblings= [],
  635. elem = elem.nextElementSibling;
  636.  
  637. while (elem) {
  638. if (elem.matches(selector)) break;
  639. if (filter && !elem.matches(filter)) {
  640. elem = elem.nextElementSibling;
  641. continue;
  642. }
  643. siblings.push(elem);
  644. elem = elem.nextElementSibling;
  645. }
  646.  
  647. return siblings;
  648.  
  649. }
  650.  
  651. //------------------ELEMENTs with certain text-------------------------
  652. function containsThis(selector,regex){
  653. let x= document.querySelectorAll(selector);
  654. return [...x].filter(e => e.childNodes && [...e.childNodes].find(n => n.nodeValue?.match(regex)))
  655. }
  656.  
  657. let x= /regex/i
  658. let element= containsThis("div",x);
  659.  
  660. //use *to search all elements
  661.  
  662. source: https://stackoverflow.com/questions/17799236/native-javascript-equivalent-of-jquery-contains-selector
  663.  
  664.  
  665.  
  666.  
  667.  
  668. //------------------JSON NOTES-------------------------
  669. JSON.stringify(object,replacerfunction,space);
  670.  
  671. Space=1=> beautified
  672. replacerfunction=> e.g array with all necessary keys ["key1","key2"] to be extracted
  673.  
  674. Visualize: http://www.bodurov.com/JsonFormatter/
  675.  
  676.  
  677.  
  678. ------OBJECT (MERGE OBJECTS IN ARRAY)
  679. let headers= Object.assign({}, ...r.headers));
  680.  
  681. GET TIME;
  682. function getTime(x){
  683. return new Date(x).toLocaleString('en-US',{
  684. hour: 'numeric',
  685. minute: 'numeric',
  686. hour12: true
  687. });
  688. }
  689.  
  690. ----MUTATION OBSERVER WHEN ELEMENT CHANGES-----
  691. let MutationObserver= window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
  692. let observer= new MutationObserver(myFunction);
  693. observer.observe(element,{
  694.  childList: true
  695.  });
  696.  
  697. function myFunction(){
  698. if(this==condition) do this;
  699. }
  700.  
  701. //Shorter-------
  702. const observer = new MutationObserver(mutation=> {
  703. //DOM was modified
  704. //Do something
  705. });
  706.  
  707. observer.observe(document.body, { subtree: true, childList: true });
  708.  
  709.  
  710.  
  711. //Typing effect css
  712. function typeIt(text,del= false){
  713. let xspan= document.createElement("span");
  714. xspan.className= "xspan";
  715. xspan.innerHTML= text;
  716.  
  717. let spanx= document.querySelector(".xspan");
  718. if(spanx && del){
  719. spanx.remove();
  720. document.body.append(xspan);
  721. }
  722. else document.body.append(xspan);
  723.  
  724. xspan.style.cssText= `
  725. width: ${text.length+.5}ch; height: 1.2em;
  726. white-space: nowrap;
  727. overflow: hidden;
  728. border-right: 3px solid;
  729. font-family: monospace;
  730. font-size: 2em;`;
  731.  
  732. let xstyle= document.createElement("style");
  733. xstyle.className= "keyframe";
  734. let stylex= document.querySelector(".keyframe");
  735. if(stylex){
  736. stylex.remove();
  737. document.body.append(xstyle);
  738. }
  739. else document.body.append(xstyle);
  740.  
  741.  
  742.  
  743. xstyle.innerHTML= `
  744. @keyframes typing {
  745. from {width: 0}
  746. }
  747.    
  748. @keyframes effect {
  749. 50%{border-color: transparent}
  750. }`;
  751.  
  752. let allx= document.querySelectorAll(".xspan");
  753. allx[allx.length-1].style.cssText+= `animation: typing 3.5s steps(${text.length}),effect 1.5s step-end infinite;`;
  754. }
  755.  
  756.  
  757. typeIt("hello my name is lol",false);
Advertisement
Add Comment
Please, Sign In to add comment