Skip to content

Instantly share code, notes, and snippets.

@vhbui02
Last active May 11, 2023 17:45
Show Gist options
  • Save vhbui02/0f684879bea8393f45fcdb5554a52cef to your computer and use it in GitHub Desktop.
Save vhbui02/0f684879bea8393f45fcdb5554a52cef to your computer and use it in GitHub Desktop.
[JavaScript] Some best practices I've learnt on Internet'

Optional chaining (?.)

Check if the obj accessed or function called, that used this operator, is undefined or null. The expression short circuits and evaluates to undefined instead of throwing an error.

obj.val?.prop
obj.val?.[expresions]
obj.func?.(args)

ALL CAPS

  • Convention to say: This data will never change after being defined here.

HTML DOM method

createElement()


HTML DOM Element

I - classList property

<div id="myDIV">
	<p>I am a myDIV.</p>
</div>
const list = document.getElementById('myDiv').classList;
list.add("myStyle")
// or list.toggle("myStyle")
// ...
.myStyle {
	color: red;
}

I.1 - add()

  • Add single class: element.classList.add("myStyle")
  • Add multiple classes : element.classList.add("firstS", "secondS", ...)

I.2 - remove()

  • Remove single class: element.classList.remove("myStyle")
  • Remove multiple classes : element.classList.remove("firstS", "secondS", ...)

I.3 - The number of class names that the element has

element.classList.length

Get all class names the element has

element.classList

Does an element has this class name?

element.classList.contains('myStyle')

Get the second class of an element

element.classList.item(1)

II - className property

Set the attribute of an element

element.className = "smt"

Get the class attribute of an element has id "myDiv"

const extractedValue = element.getElementById("myDiv").className;

Toggle between 2 class names (used only for single class name) (not practical)

if (element.className == 'old smt') {
	element.className = 'new smt';
} else {
	element.className = 'old smt';
}

Combine these method to create some use cases

1 - Toggle between classes to create a dropdown button

Method 1: specify INSIDE js file

document.getElementById('myBtn').onclick = () => {
	myFunc();
}

const myFunc = () => {
	document.getElementById('myBtn').classList.toggle('show-smt');
}

Method 2: specify INSIDE HTML file, people tend to not doing this since HTML can't possibly know what's inside JS file

<button onclick="myFunc()">Click me!</button>

2 - Create a sticky navigation bar

<nav class="navbar"></nav>
const navbar = document.getElementById("navbar");

const sticky = navbar.offsetTop;

// add the sticky class to the navbar when reach its scroll position
// remove it when you leave the scroll position
const myFunc = () => {
	if (window.pageYOffsetY >= sticky) {
   	navbar.classList.add("sticky")
   } else {
     	navbar.classList.remove("sticky")
   }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment