Skip to content

Instantly share code, notes, and snippets.

@Shakil-Shahadat
Last active June 24, 2024 02:55
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 1.05
for ( x of document.querySelectorAll( 'a' ) ) 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 / in' & 'for / of' loop
//-------------------------------------------------------
let fruits = [ 'apple', 'orange', 'mango' ];
// for / of loop
for ( e of fruits )
{
// e is now an element of the array
console.log( e ); // Output: apple, orange, mango
}
// for / in loop
for ( i in fruits )
{
// i is now an index of the array
console.log( i ); // Output: 0, 1, 2
}
//-------------------------------------------------------
// Timing Events
//-------------------------------------------------------
// One time event
setTimeout( function(){}, 1000 );
setTimeout( () => {}, 1000 );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
// Repetitive event
setInterval( function(){}, 1000 );
setInterval( () => {}, 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
//-------------------------------------------------------
// Create an Element
//-------------------------------------------------------
// Create an Element
let ele = document.createElement( 'div' ); // Replace 'div' with the required element
// Insert Text
ele.innerText = 'Hello World!';
// or
ele.innerHTML = 'Hello World!';
// or, not recommended
let textNode = document.createTextNode( 'Hello World!' ); // Create a text node
ele.appendChild( textNode );
// Set Attribute
ele.setAttribute( 'class', 'demoClass' );
// or, not recommended
let att = document.createAttribute( 'class' ); // Create a 'class' attribute
att.value = 'demoClass'; // Set the value of the class attribute
ele.setAttributeNode( att );
// Add an Event
ele.onchange = function() // Replace 'onchange' with the required event
{
}
// Add event listener example
ele.addEventListener( 'change', function(){} ); // Replace 'change' with the required event
// Insert an Element Inside the Created Element
ele.append( anotherElement ); // Warning: 'anotherElement' element must exist beforehand
// 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
// Add references.
// onchange => eventname
// Write an article based on this.
//-------------------------------------------------------
// Arrow Functions
//-------------------------------------------------------
/*
Arrow functions 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'
3. When there are more than one parameter, it'll be a comma separated list
enclosed by first bracket. E.g. '( age, height, weight )'.
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.
Examples
1. () => a + b
2. a => a + b
3. ( a, b ) => { a++; return a + b; }
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
*/
//-------------------------------------------------------
// 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( function(){ location.reload(); }, 30 * 1000 ); // Reload at every 30 seconds
// Alternative
setTimeout( () => { location.reload(); }, 30 * 1000 ); // Reload at every 30 seconds
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
//-------------------------------------------------------
// Location Related Codes
//-------------------------------------------------------
// Get current location
const currentLocation = location.href;
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Window/location
// Redirect to new location
location.href = 'https://example.com/';
// Ref: https://www.javascripttutorial.net/javascript-bom/javascript-redirect/
// Open a new tab
open( 'https://example.com/' );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Window/open
//-------------------------------------------------------
// 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:
// 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();
// See also https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
// https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
//-------------------------------------------------------
// 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 );
}
}
//-------------------------------------------------------
// 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 );
}
}
//-------------------------------------------------------
// Miscellaneous Codes
//-------------------------------------------------------
// Add event listener
targetElement.addEventListener( 'change', function(){} ); // Replace 'change' with the required event
// 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
// Encode a string
const encodedString = encodeURIComponent( 'Hello World!' );
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
// 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 );
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText
// Text area auto grow script
for ( e of document.querySelectorAll( 'textarea' ) )
{
for ( 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 the number of links in the title
document.querySelector( 'title' ).innerText += ' [ ' + document.querySelectorAll( 'a' ).length + ' ]';
// A list of months in JS Array
months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];
// Add CSS Styles from JavaScript
let s = document.createElement( 'style' );
s.innerText =
`
.box
{
display: none;
}
`;
document.head.appendChild( s );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment