Swastik Yadav


Navigate back to the homepage

9 useful code snippets for everyday JavaScript development || Part 1

Swastik Yadav
February 15th, 2023 · 2 min read

Hello Everyone!

Welcome to this JavaScript snippets post, In this post we will look at some of the most common JavaScript snippets which will help you with your everyday JavaScript development.

You can always use 3rd party utility libraries, but knowing these vanilla JavaScript snippets is always beneficial.

And these snippets are so easy and small, that you should always prefer them instead of a 3rd party utility library.

This series is divided in 2 parts, this post is the first one.

Now, let’s get started.

1. HTTPS Redirect

Redirect HTTP protocol to HTTPS protocol.

1const httpsRedirect = () => {
2 if (location.protocol !== 'https:')
3 location.replace('https://' + location.href.split('//')[1]);
7// Redirect from http://mydomain.com to https://mydomain.com
  • First we find out the protoco with window.location.protocol.
  • Then, if protocol is HTTP, we replace the URL with HTTPS protocol.
  • And, reload the page.

Note: Going back via brower’s back button won’t go to http, as it is replaced in the history.

2. Input value as a Number

Ever wanted an input value as Number and not string? By default we always get input value from JS as string. Then we convert it to Number.

The purpose of the number type is that mobile browsers use this for showing the right keyboards and some browsers use this for validation purposes. For example the email type will show a keyboard with the @ and ’.’ on the keyboard and number will show a numeric keyboard.

But, there is a better way to get the input value as Number.

1const numInput = document.getElementById('num-input');
3let num;
4// Bad: parseFloat() converts the string to a number
5num = parseFloat(numInput.value);
7// Good: returns a numeric value
8num = numInput.valueAsNumber;

HTMLInputElement.valueAsNumber returns a numeric value or NaN from the input value.

3. Handle Click Outside

If you want to do something when user clicks outside of the specified element, this snippet is going to save your day.

1const onClickOutside = (elementId, callback) => {
2 const element = document.getElementById(elementId);
4 document.addEventListener("click", (e) => {
5 if (!element.contains(e.target)) callback();
6 });
9onClickOutside("red-box", () => console.log("Clicked outside red box"));
11document.addEventListener("DOMContentLoaded", onClickOutside);
12// Will log 'Hello' whenever the user clicks outside of #my-element
  • addEventListener is being used to listen to the click event.
  • Node.contains() check if the clicked element is outside of the specified element.
  • DOMContentLoaded event listener makes sure that the onClickOutside function is invoked only after HTML is mounted on the DOM.

4. Handle Scroll Stop

Maybe, there is something you want to do, when user stops scrolling. Here is a snippet to help you with that.

1const onScrollStop = callback => {
2 let isScrolling;
3 window.addEventListener(
4 'scroll',
5 e => {
6 clearTimeout(isScrolling);
7 isScrolling = setTimeout(() => {
8 callback();
9 }, 150);
10 },
11 false
12 );
15onScrollStop(() => {
16 console.log('The user has stopped scrolling');
  • addEventListener is used to listen to the scroll event.
  • Use setTimeout to wait for 150ms before invoking the callback.
  • clearTimeout is used to clear the timeout, if new scroll event is fired under 150ms.

5. Detect if CapsLock is on

Check if user’s CapsLock is on or off.

1// Assume, el is an input element, and msg is a p tag to show message.
3el.addEventListener('keyup', e => {
4 msg.style = e.getModifierState('CapsLock')
5 ? 'display: block'
6 : 'display: none';
  • KeyboardEvent.getModifierState() is used to determine the state of the CapsLock key on users keyboard.

So, that is it for this post. If you anyhow liked this post, make sure to show your support.

I will see you in the next part of this post with 4 more useful code snippets for everyday JavaScript development.

I also run a weekly newsletter, so you can join me there also.

Thank You!

More articles from Swastik Yadav

Understand call, apply, and bind functions in JavaScript like never before.

In this post, we'll take a detailed look at how call, apply, and bind work in JavaScript.

January 20th, 2023 · 1 min read

Understanding the need for useEvent() React hook.

In this post, let's try to understand the need of *useEvent* React hook and we will see what problem the React team is trying to solve with this hook.

January 7th, 2023 · 1 min read

Developers, Double your income without competing against thousands of resumes by building your social presence.

Learn to bypass all the competition. Let the opportunities come to you instead of you mindlessly running behind it. This is how I went from 9LPA to 18LPA.

© 2021–2023 Swastik Yadav
Link to $https://twitter.com/swastikb380Link to $https://github.com/SwastikyadavLink to $https://www.linkedin.com/in/swastikyadav/