Skip to content

Instantly share code, notes, and snippets.

@Shakil-Shahadat
Last active January 22, 2025 06:05
Show Gist options
  • Save Shakil-Shahadat/7009056693ac71bac724c8fb8e9de810 to your computer and use it in GitHub Desktop.
Save Shakil-Shahadat/7009056693ac71bac724c8fb8e9de810 to your computer and use it in GitHub Desktop.
★ Miscellaneous JavaScript Codes
//-------------------------------------------------------
// Add target="_blank" attribute to all anchor tags
//-------------------------------------------------------
// Add target="_blank" to all anchor tags, v 2.1
for ( let x of document.links ) x.setAttribute( 'target', '_blank' );
//-------------------------------------------------------
// Functions to shorten querySelector* calls
//-------------------------------------------------------
function qs( cls )
{
return document.querySelector( cls );
}
function qsa( cls )
{
return document.querySelectorAll( cls );
}
// Examples
qs( '.box' ).innerText = 'Hello World!';
qsa( '.box' )[ 0 ].innerText = 'Hello Universe!';
//-------------------------------------------------------
// Summary of 'for / of' & 'for / in' loop
//-------------------------------------------------------
let fruits = [ 'apple', 'orange', 'mango' ];
// for / of loop
for ( let e of fruits )
{
// e is now an element of the array
console.log( e ); // Output: apple, orange, mango
}
// for / in loop
for ( let i in fruits )
{
// i is now an index of the array
console.log( i ); // Output: 0, 1, 2
}
//-------------------------------------------------------
// Timing Events
//-------------------------------------------------------
// One time event
setTimeout( () => {}, 1000 );
setTimeout( function(){}, 1000 );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
// Repetitive event
setInterval( () => {}, 1000 );
setInterval( function(){}, 1000 );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/setInterval
// If these need to be canceled, then assign them
// to a variable and then clear them like this.
clearTimeout( assignedVar );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout
clearInterval( assignedVar );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/clearInterval
//-------------------------------------------------------
// Detect single and multiple keypress events
//-------------------------------------------------------
// Detect single keypress event
document.addEventListener( 'keyup', ( event ) => {
if ( event.key == 'Escape' ) {
console.log( 'Hello World!' );
}
});
// Detect multiple keypress event
let keysPressed = {};
document.addEventListener( 'keydown', ( event ) => {
keysPressed[ event.key ] = true;
if ( keysPressed[ 'Control' ] && event.key == 'q' ) {
console.log( event.key );
}
if ( keysPressed[ 'Control' ] && event.key == 'b' ) {
console.log( event.key );
}
});
document.addEventListener( 'keyup', ( event ) => {
delete keysPressed[ event.key ];
});
// Ref: https://medium.com/@rushikesh1s/detect-single-and-multiple-keypress-events-in-javascript-ad2164dbddb3
//-------------------------------------------------------
// Create an Element
//-------------------------------------------------------
// Create an Element
let ele = document.createElement( 'div' ); // Replace 'div' with the required element
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
// Insert Text
ele.innerText = 'Hello World!';
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
// or
ele.innerHTML = 'Hello World!';
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
// or, not recommended
let textNode = document.createTextNode( 'Hello World!' ); // Create a text node
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode
ele.appendChild( textNode );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
// Set Attribute
ele.setAttribute( 'class', 'demoClass' );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
// or, not recommended
let att = document.createAttribute( 'class' ); // Create a 'class' attribute
// https://developer.mozilla.org/en-US/docs/Web/API/Document/createAttribute
att.value = 'demoClass'; // Set the value of the class attribute
ele.setAttributeNode( att );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttributeNode
// Add an Event
ele.onchange = () => {}
ele.onchange = function() {}
// Replace 'onchange' with the required event
// Add an event with addEventListener
ele.addEventListener( 'change', () => {} );
ele.addEventListener( 'change', function(){} );
// Replace 'change' with the required event
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
// Insert an Element Inside the Created Element
ele.append( anotherElement ); // Warning: 'anotherElement' element must exist beforehand
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/append
// Add the Element to Another Element
document.querySelector( '.className' ).append( ele ); // Warning: 'className' class must exist beforehand
// Add the Element to the Page
document.body.append( ele );
// ToDo:
// Other methods for insertion: prepend, insertbefore
// Write an article based on this.
//-------------------------------------------------------
// Arrow Function
//-------------------------------------------------------
/*
ToDo: Move this to JavaScript Tutorial
Arrow function is an alternative way of writing anonymous function.
It has two parts: parameter part and body part.
They are written together along with '=>' in the middle.
Parameter Part => Body Part
Parameter part can be of 3 types.
1. When there is no parameter then it will be just '()'.
2. When there is only one parameter, it'll be just that parameter like 'age'.
Can be enclosed by first bracket too like '( age )'.
3. When there are more than one parameter, it'll be a comma separated list
enclosed by first bracket. E.g. '( age, height, weight )'.
ToDo: Add a table of examples.
Body part can be of 2 types.
1. If the function has only a return statement and nothing else, then the
body part will be just the return statement without the 'return' keyword.
2. Otherwise, it'll be the same as the function along with the second brackets.
ToDo: Add a table of examples.
Combind Examples,
1. () => a * a
2. a => a * a
3. ( a ) => a * a
4. ( a, b ) => { a++; return a + b; }
ToDo: Turn this into a table.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
*/
//-------------------------------------------------------
// DOM Traversal
//-------------------------------------------------------
document.querySelector( '.box' ).parentElement
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement
document.querySelector( '.box' ).parentNode
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode
document.querySelector( '.box' ).childNodes
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes
document.querySelector( '.box' ).children
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/children
document.querySelector( '.box' ).firstChild
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Node/firstChild
document.querySelector( '.box' ).lastChild
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Node/lastChild
document.querySelector( '.box' ).firstElementChild
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/firstElementChild
document.querySelector( '.box' ).lastElementChild
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/lastElementChild
document.querySelector( '.box' ).attributes
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes
document.querySelector( '.box' ).closest( '.list' )
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
document.querySelector( '.box' ).matches( '.list' )
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
document.querySelector( '.box' ).nextElementSibling
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling
document.querySelector( '.box' ).previousElementSibling
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Node/previousSibling
// Ref: https://zellwk.com/blog/dom-traversals/
//-------------------------------------------------------
// Page Reload Related Codes
//-------------------------------------------------------
// Reload current page
location.reload();
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Location/reload
// Reload page at an interval
setTimeout( () => { location.reload(); }, 30 * 1000 ); // Reload at every 30 seconds
// Alternative
setTimeout( function(){ location.reload(); }, 30 * 1000 ); // Reload at every 30 seconds
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
//-------------------------------------------------------
// Location Related Codes
//-------------------------------------------------------
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Location
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Window/location
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/location
// Get current location
console.log( location.href );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Location/href
// Redirect to a new location
location.href = 'https://example.com/';
// Ref: https://www.javascripttutorial.net/javascript-bom/javascript-redirect/
// Or
location.assign( 'https://example.com/' );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
// Open a new tab
open( 'https://example.com/' );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Window/open
// Get protocol
console.log( location.protocol );
// https:
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Location/protocol
// Get hostname
console.log( location.hostname );
// example.com
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Location/hostname
// Or
console.log( document.domain ); // Obsolete
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/domain
// Get path
console.log( location.pathname );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Location/pathname
//-------------------------------------------------------
// Regular Expression / Regex
//-------------------------------------------------------
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
// Test the existance of a string
let myString = 'Hello, World!';
let myRegex = /Hello/;
let result = myRegex.test( myString ); // Returns true / false
console.log( result );
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
// Extract a part of a string
let myString = 'Hello, World!';
let myRegex = /Hello/;
let result = myString.match( myRegex );
console.log( result );
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
// Also, check this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
//-------------------------------------------------------
// localStorage / sessionStorage
//-------------------------------------------------------
// Check for localStorage / sessionStorage
if ( typeof( Storage ) !== 'undefined' )
{
console.log( 'Storage Exists!' );
}
else
{
console.log( 'Storage doesn\'t Exists!' );
}
// localStorage Examples
// Store
localStorage.setItem( 'name', 'Smith' );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
// Retrieve
console.log( localStorage.getItem( 'name' ) );
// Remove
localStorage.removeItem( 'name' );
// Removing all the localStorage items
localStorage.clear();
// sessionStorage Examples
// Store
sessionStorage.setItem( 'name', 'Smith' );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
// Retrieve
console.log( sessionStorage.getItem( 'name' ) );
// Remove
sessionStorage.removeItem( 'name' );
// Removing all the sessionStorage items
sessionStorage.clear();
// See also https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
//-------------------------------------------------------
// Ajax POST request with data
//-------------------------------------------------------
let data1 = 'Hello World!';
let data2 = 'Hello Universe!';
let http = new XMLHttpRequest();
http.open( 'POST', 'post.php' );
http.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
http.send( 'data1=' + data1 + '&data2=' + data2 );
http.onreadystatechange = function()
{
if ( http.readyState == 4 && http.status == 200 )
{
console.log( http.responseText );
}
}
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readystatechange_event
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText
//-------------------------------------------------------
// Ajax GET request
//-------------------------------------------------------
let http = new XMLHttpRequest();
http.open( 'GET', 'get.php' );
http.send();
http.onreadystatechange = function()
{
if ( http.readyState == 4 && http.status == 200 )
{
console.log( http.responseText );
}
}
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readystatechange_event
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText
//-------------------------------------------------------
// Text area auto grow script
//-------------------------------------------------------
for ( let e of document.querySelectorAll( 'textarea' ) )
{
for ( let s of [ 'keyup', 'keydown', 'change', 'cut', 'paste', 'drop' ] )
{
e.addEventListener( s, resizeTextArea );
}
}
function resizeTextArea()
{
this.style.height = 'auto';
this.style.height = this.scrollHeight + 'px';
}
//-------------------------------------------------------
// Add CSS Styles from JavaScript
//-------------------------------------------------------
let s = document.createElement( 'style' );
s.innerText =
`
.box
{
display: none;
}
`;
document.head.appendChild( s );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
//-------------------------------------------------------
// Encode / Decode a string
//-------------------------------------------------------
// encodeURI / decodeURI
const encodedString = encodeURI( 'Hello World!' );
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
const decodedString = decodeURI( 'Hello World!' );
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI
// encodeURIComponent / decodeURIComponent
const encodedString = encodeURIComponent( 'Hello World!' );
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
const decodedString = decodeURIComponent( 'Hello World!' );
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent
//-------------------------------------------------------
// Miscellaneous Codes
//-------------------------------------------------------
// Add event listener
targetElement.addEventListener( 'change', () => {} );
targetElement.addEventListener( 'change', function(){} );
// Replace 'change' with the required event
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
// Add event listener to a group of elements
for ( let e of document.querySelectorAll( '.box' ) )
{
e.addEventListener( 'click', function(){
});
}
// Access data attribute value
// <div class="box" data-secret-info="Hello World!">Hello Universe!</div>
console.log( document.querySelector( '.box' ).dataset.secretInfo );
// Ref: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
// Check if an element exists
if ( document.body.contains( document.querySelector( '.box' ) ) )
{
console.log( 'Element exists!' );
}
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Node/contains
// Copy to clipboard
navigator.clipboard.writeText( 'Hello World!' );
navigator.clipboard.writeText( document.querySelector( '.targetClass' ).value );
function copyToClipboard()
{
navigator.clipboard.writeText( document.querySelector( '.targetClass' ).value );
}
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText
// Add the number of links in the title
document.title += ' [ ' + document.links.length + ' ]';
// document.querySelector( 'title' ).innerText += ' [ ' + document.querySelectorAll( 'a' ).length + ' ]';
// Focus on an input
// <input type="text" class="data" size="40">
document.querySelector( '.data' ).focus();
// Explode / String to Array
const text = 'The quick brown fox jumps over the lazy dog.';
const words = text.split( ' ' );
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
// Implode / Array to String
const elements = [ 'Fire', 'Air', 'Water' ];
console.log( elements.join() );
// Expected output: 'Fire,Air,Water'
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
// Lowercase / Uppercase
let result = text.toLowerCase();
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase
let result = text.toUpperCase();
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase
// Delayed Alert
setTimeout( () => {
alert( 'Hello World!' );
}, 50 );
// A list of months in JS Array
months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment