/ Gists / JavaScript

Gists - JavaScript

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

On gists

Colorpicker + event

JavaScript

ex.html #

<body>
	<input type="color" id="color" value="#c1e0ff" />
</body>


<script>

const color = document.querySelector('#color')
const div = document.body

color.addEventListener('input', () => {
	div.style.backgroundColor = color.value
})

color.dispatchEvent(new Event('input'));

</script>

On gists

Function object with inside small functions

JavaScript-OOP JavaScript

example.js #

var Wrapper = (function () {
	this.A = () => {
		console.log('A');
	}
	this.B = () => {
		console.log('B');
	}
	
	return {
		A2: this.A,
		B2: this.B
	}

	// or return this
})();


Wrapper.B2(); // B

On gists

native js + trigger event

JavaScript

event.js #

const e = new Event('change')
const element = document.querySelector('#' + this.fakeFileId)
element.dispatchEvent(e)