JS - Other

Rounds A Number To The Nearest Integer

Math.round(number)

Rounds A Number UPWARDS To The Nearest Integer

Math.ceil(number)

Saving Text to Session If The Page Is Accidentally Refreshed

Get the text field that you want to track

let field = document.getElementById('field');


Assign value to the field if accidentally refreshed the page

if(sessionStorage.getItem('autosave')){
 field.value = sessionStorage.getItem('autosave');
}


Save value to session when field value change

field.addEventListener('change', function(){
 sessionStorage.setItem('autosave', field.value);
});

Screen Capture API

The Screen Capture API, as the name suggests, allows you to capture the contents of a screen, making the process of building a screen recorder a piece of cake.


You need a video element to display the captured screen. The start button will start the screen capture.

<video id="preview" autoplay>
  Your browser doesn't support HTML5.
</video>
<button id="start" class="btn">Start</button>


const previewElem = document.getElementById("preview");
const startBtn = document.getElementById("start");

async function startRecording() {
  previewElem.srcObject =
    await navigator.mediaDevices.getDisplayMedia({
      video: true,
      audio: true,
    });
}

startBtn.addEventListener("click", startRecording);

Screen Orientation API

The Screen Orientation API allows you to check the current orientation of the screen and even lock it to a specific orientation.

async function lockHandler() {
  await screen.orientation.lock("portrait");
}

function releaseHandler() {
  screen.orientation.unlock();
}

function getOrientation() {
  return screen.orientation.type;
}


Screen Wake Lock API

Ever wondered how YouTube prevents the screen from being switched off while playing the video? Well, that's because of the Screen Wake Lock API.

let wakeLock = null;

async function lockHandler() {
  wakeLock = await navigator.wakeLock.request("screen");
}

async function releaseHandler() {
  await wakeLock.release();
  wakeLock = null;
}


NOTE: You can only use the Screen Wake Lock API if the page is already visible on the screen. Otherwise, it would throw an error.

Scroll To Bottom of The Page

window.scrollTo({ top: document.body.scrollHeight, behavior: "smooth" });

Scroll To Top of The Page

goToTop = () => window.scrollTo(0, 0);
window.scrollTo({ top:0, behavior: 'smooth'});

Select all checkbox

//select all checkbox
$('.thCheckbox').on('click', function () {
    $('table').find('tbody .tdCheckbox').prop('checked', this.checked);
});

//checkbox listing
$('.tdCheckbox').on('change', function (e) {
    tdCheckboxChecked = $('table').find('tbody .tdCheckbox:checkbox:checked').length;
    $('.thCheckbox').prop('checked', (tdCheckboxChecked === $('table').find('tbody .tdCheckbox').length));
})

Selection API

The Selection API provides methods to access and manipulate the text or content that the user has selected on a webpage.


Core Components

  • window.getSelection(): Returns a Selection object representing the user's selected text.
  • Range: Represents a part of the document (start and end points).


Example: Get Selected Text

document.addEventListener("mouseup", () => {
    let selection = window.getSelection();
    console.log(selection.toString()); // Logs selected text
});


Example: Modify Selection

You can clear or manipulate selections programmatically.

let selection = window.getSelection();
selection.removeAllRanges(); // Clears the selection

let range = document.createRange();
let p = document.querySelector("p");
range.selectNodeContents(p); // Select the entire paragraph content

selection.addRange(range); // Apply the range as the new selection

Send different types of data with the Fetch API

// Sending Form Data
const formData = new FormData();
formData.append('key', 'value');

// Sending Images
const image = new Blob([imageFile], {type: 'image/jpeg'});

fetch('https://...', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Session Storage

Save data to session storage

sessionStorage.setItem('key', 'value');


Get saved data from session storage

let data = sessionStorage.getItem('key');


Remove saved data from session storage

sessionStorage.removeItem('key');


Remove all saved data from session storage

sessionStorage.clear();