/ Gists / JavaScript

Gists - JavaScript

On gists

Simple rating (odometer)

JavaScript CSS CSS trick

example.html #

	<section>
	<button id="minus">-</button>
	<div>
		<span style="--state: -10">- 9-8 -7 -6 -5 -4 -3 -2 -1 0 +1 +2 +3 +4 +5 +6 +7 +8 +9</span>
	</div>
	<button id="plus">+</button>
		</section>

On gists

Function called only once

JavaScript

example.js #

const myFunc = () => {
  if (myFunc.fired) {
    return;
  }
  myFunc.fired = true;
  //...
};

On gists

Check if the array contains a value / get index

JavaScript JS oneliners

ex.js #

const array = [ 'fatfish', 'hello', 'world', 24 ]
console.log(array.indexOf('fatfish')) // 0
console.log(array.indexOf('medium')) // -1



const array = [
  {
    name: 'fatfish'
  },
  {
    name: 'hello'
  },
  {
    name: 'world'
  },
]
const index = array.findIndex((it) => it.name === 'fatfish') // 0

On gists

Flatten multi-layer arrays

JavaScript JS oneliners

solution1.js #

const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
const flattenArray = (array) => {
  return array.reduce((res, it) => {
    return res.concat(Array.isArray(it) ? flattenArray(it) : it)
  }, [])
}
console.log(flattenArray(array)) // [1, 2, 3, 4, 5]

On gists

Shuffle the values of an array randomly

JavaScript JS oneliners

ex.js #

const prizes = [ 'A', 'B', 'C', 'D' ]
prizes.sort(() => 0.5 - Math.random())


On gists

How to get index of element as child relative to parent with JavaScript?

JavaScript

example.js #

const lis = [...document.querySelectorAll("#wizard > li")];

lis.forEach((li) => {
  li.addEventListener("click", () => {
    const index = lis.indexOf(li);
    console.log(index);
  });
});

On gists

Content from Iframe

JavaScript

example.js #

// https://thewebdev.info/2022/04/22/how-to-get-the-bodys-content-of-an-iframe-in-javascript/
const iframe = document.querySelector("#id_description_iframe");
const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
const iframeContent = iframeDocument.querySelectorAll("#frameBody");

On gists

Add and Remove Rules Directly to Stylesheets

JavaScript

usage.js #

function addCSSRule(sheet, selector, rules, index) {
	if(sheet.insertRule) {
		sheet.insertRule(selector + "{" + rules + "}", index);
	}
	else {
		sheet.addRule(selector, rules, index);
	}
}

// Use it!
addCSSRule(document.styleSheets[0], "header", "float: left");

On gists

CSS variables (get/set + javascript)

Popular ⭐ JavaScript CSS CSS trick

usage.js #

// Getting a CSS Variable's Value
getComputedStyle(document.documentElement) // or specific element
    .getPropertyValue('--my-variable-name'); // #999999
    
  
// Setting a CSS Variable's Value
document.documentElement.style // or specific element
    .setProperty('--my-variable-name', 'pink');
    
    
// OR
var root = document.querySelector(':root'); // = document.documentElement