JS - Other

Local Storage

Syntax for saving data to local storage

localStorage.setItem('myItem', 'myItemValue');


Syntax for reading the local storage item

const item = localStorage.getItem('myItem');


Syntax for removing the local storage item

localStorage.removeItem('myItem');


Syntax for removing all the local storage items

localStorage.clear();

Log Value With Variable Name

console.log({var});

Math.floor()

~~number

Math.pow()

2**3

Merge arrays

const arr1 = [1, 2, 3];
const arr2 = [9, 8, 7];

const arr3 = [...arr2];
const mergedArr = [...arr1, ...arr2];

console.log(arr3); //[9, 8, 7]
console.log(mergedArr); //[1, 2, 3, 9, 8, 7]

Notification API

<button class="notify">Notify Me</button>

<script>
  $(".notify").click(function () {
    notify();
  })

  function notify() {
    (async () => {
      // create and show the notification
      const showNotification = () => {

        // create a new notification
        const notification = new Notification('Title', {
          body: 'Description',
          icon: 'ImagePath'
        });

        // close the notification after 10 seconds
        setTimeout(() => {
          notification.close();
        }, 10 * 1000);

        // navigate to a URL when clicked
        notification.addEventListener('click', () => {
          //Do something after click the notification
        })
      }

      // show an error message
      const showError = () => {
        //Do something if error
      }

      // check notification permission
      let granted = false;

      if (Notification.permission === 'granted') {
        granted = true;
      } 
      else if (Notification.permission !== 'denied') {
        let permission = await Notification.requestPermission();
        granted = qwe === 'granted' ? true : false; 
      }

      // show notification or error
      granted ? showNotification() : showError();
    })();
  }
</script>

Page Visibility API

The Page Visibility API provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page.


This is especially useful for saving resources and improving performance by letting a page avoid performing unnecessary tasks when the document isn't visible.


HTML

<audio
  controls
  src="https://mdn.github.io/webaudio-examples/audio-basics/outfoxing.mp3"></audio>


JavaScript

const audio = document.querySelector("audio");


let playingOnHide = false;


document.addEventListener("visibilitychange", () => {
  if (document.hidden) {
    playingOnHide = !audio.paused;
    audio.pause();
  } else {
    // Page became visible! Resume playing if audio was "playing on hide"
    if (playingOnHide) {
      audio.play();
    }
  }
});

Password Validator

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* Style all input fields */
input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  margin-top: 6px;
  margin-bottom: 16px;
}

/* Style the submit button */
input[type=submit] {
  background-color: #04AA6D;
  color: white;
}

/* Style the container for inputs */
.container {
  background-color: #f1f1f1;
  padding: 20px;
}

/* The message box is shown when the user clicks on the password field */
#message {
  display:none;
  background: #f1f1f1;
  color: #000;
  position: relative;
  padding: 20px;
  margin-top: 10px;
}

#message p {
  padding: 10px 35px;
  font-size: 18px;
}

/* Add a green text color and a checkmark when the requirements are right */
.valid {
  color: green;
}

.valid:before {
  position: relative;
  left: -35px;
  content: "✔";
}

/* Add a red text color and an "x" when the requirements are wrong */
.invalid {
  color: red;
}

.invalid:before {
  position: relative;
  left: -35px;
  content: "✖";
}
</style>
</head>
<body>

<h3>Password Validation</h3>
<p>Try to submit the form.</p>

<div class="container">
  <form action="/action_page.php">
    <label for="usrname">Username</label>
    <input type="text" id="usrname" name="usrname" required>


    <label for="psw">Password</label>
    <input type="password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@$!%*?&]).{8,}" title="Must contain at least one number, one uppercase and lowercase letter, one special character, and at least 8 or more characters" required>
    
    <input type="submit" value="Submit">
  </form>
</div>

<div id="message">
  <h3>Password must contain the following:</h3>
  <p id="letter" class="invalid">A <b>lowercase</b> letter</p>
  <p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
  <p id="number" class="invalid">A <b>number</b></p>
  <p id="special" class="invalid">A <b>special character</b></p>
  <p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>
				
<script>
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var special = document.getElementById("special");
var length = document.getElementById("length");

// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
  document.getElementById("message").style.display = "block";
}

// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
  document.getElementById("message").style.display = "none";
}

// When the user starts to type something inside the password field
myInput.onkeyup = function() {
  // Validate lowercase letters
  var lowerCaseLetters = /[a-z]/g;
  if(myInput.value.match(lowerCaseLetters)) {  
    letter.classList.remove("invalid");
    letter.classList.add("valid");
  } else {
    letter.classList.remove("valid");
    letter.classList.add("invalid");
  }
  
  // Validate capital letters
  var upperCaseLetters = /[A-Z]/g;
  if(myInput.value.match(upperCaseLetters)) {  
    capital.classList.remove("invalid");
    capital.classList.add("valid");
  } else {
    capital.classList.remove("valid");
    capital.classList.add("invalid");
  }


  // Validate numbers
  var numbers = /[0-9]/g;
  if(myInput.value.match(numbers)) {  
    number.classList.remove("invalid");
    number.classList.add("valid");
  } else {
    number.classList.remove("valid");
    number.classList.add("invalid");
  }
  
  // Validate special characters
  var specialCharacters = /[@$!%*?&]/g;
  if(myInput.value.match(specialCharacters)) {  
    special.classList.remove("invalid");
    special.classList.add("valid");
  } else {
    special.classList.remove("valid");
    special.classList.add("invalid");
  }
  
  // Validate length
  if(myInput.value.length >= 8) {
    length.classList.remove("invalid");
    length.classList.add("valid");
  } else {
    length.classList.remove("valid");
    length.classList.add("invalid");
  }
}
</script>

</body>
</html>

Play / Pause Video by Event

$("ID/CLASS/TAG").EVENT(function() {
  if (this.paused) { this.play(); }
  else { this.pause(); }
});

POST Request with Async/Await

There is a term used for async/await called Syntactic Sugar. Async/Await are also built on top of Promises. Because it provides a much cleaner and easy-to-use syntax with normal javascript function to make an API call they are named as syntactic sugar.


Let's see how it uses a javascript function to make asynchronous calls and return promises.

async function getCountriesList() {
  try {
    let response = await fetch("https://restcountries.com/v3.1/all");
    let data = await response.json();
    console.log("Response Data: ", data);
  } catch(error) {
    console.error("Error: ", error);
  }
}
getCountriesList();


As you can see, the more you explore different methods the more easy it is to make an API call. The above example uses async the keyword at the beginning of the function to mark this function as asynchronous, while making a request and waiting for the server response we use await the keyword. Also, I have wrapped the whole example in try/catch a block to get more control over the code and Error messages.

POST Request with Fetch API

fetch("https://...", {
  method: "POST",
  body: JSON.stringify({
    userId: 1,
    title: "...",
    completed: false
  }),
  headers: {
    "Content-type": "application/json; charset=UTF-8"
  }
})
  .then((response) => response.json())
  .then((json) => console.log(json));

POST Request with JavaScript Promises

In javascript Promises are the new addition in ES6. These promises make it a lot easier to work with asynchronous tasks, like API calls.


See how to make an asynchronous call using Promises:

const promiseFetchCountries = () => {
  return new Promise((resolve, reject) => {
    fetch("https://restcountries.com/v3.1/all")
      .then((response) => {
        if (response.ok) {
          return response.json();
        } else {
          reject("Failed to fetch data");
        }
      })
      .then((data) => resolve(data))
      .catch((error) => reject(error));
  });
};

promiseFetchCountries()
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));


The new Promise() object is initialized which takes a function with resolve and reject methods as an argument. These methods are used to mark the response as resolved (success) or reject (failed).


To wait for an asynchronous call, and to manipulate the output result, JavaScript promises come with changing methods like .then() and .catch() , these methods wait until the request is completed.