5 Useful JavaScript Snippets You Should Know About

In this article, we’re going to explore 5 different JavaScript snippets that you can use in your projects. Snippets are definitely useful to keep on hand, as you may never know when you’re going to need them, and there’s no point in rewriting code every time you need to get something done.

1. Prevent Pasting

While it’s quite annoying to do this for your users (in our opinion), you might want to implement this feature on your websites anyway, perhaps to prevent copy-pasting passwords on registration. Disable pasting within an input by adding the script below to an input tag.

<input id="no-paste" placeholder="Type text here" />

<script>
  const pasteBox = document.getElementById("no-paste");
  pasteBox.onpaste = e => {
    e.preventDefault();
    return false;
  };
</script>

2. Get The Current URL

Getting the current URL can be useful for a number of reasons, such as dynamically changing or loading content based on specific parameters of the URL. Here’s a function which allows you to grab the current URL of the page you are on.

const getURL = () => {
  console.log(window.location.href);
}

getURL(); // https://blog.javascripttoday.com/

3. Toggle Password Visibility

You begin typing your password and accidentally click on a wrong key. Now you have no idea what’s in the password field… If only there was some way to see what you’ve already typed. (Of course you can always go in the dev tools and change the password value to ‘text’).

However, we can just implement a toggle feature, like so:

<div class="password-container">
  <label for="password">Password:</label>
  <input type="password" id="password" placeholder="Enter your password">
  <button id="togglePassword">Show/Hide</button>
</div>

<script>
const passwordInput = document.getElementById('password');
const togglePassword = document.getElementById('togglePassword');
togglePassword.addEventListener('click', function() {
  const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
  passwordInput.setAttribute('type', type);
});
</script>

4. Generate Random Hex Codes

For whatever reason, you might want to generate some random colors for an application. The following function will enable you to do just that!

const getRandomColor = () => {
  document.body.style.backgroundColor = 
      `#${Math.floor(Math.random() * 16777215).toString(16)}`;
};

getRandomColor(); // Changes the background color of the document

You can also save the value into local storage, enabling the color to be “saved” until another function call is made, and so on.

5. Get the time

Displaying the time for your users may be beneficial per your application. Here’s a little snippet which allows you to do just that.

<div id="currentTime"></div>

<script>
  const displayCurrentTime = () => {
    const currentTime = new Date().toLocaleTimeString();
    document.getElementById('currentTime').innerText = `Current time: ${currentTime}`;
  };

  displayCurrentTime();

  setInterval(displayCurrentTime, 250); 
</script>

Conclusion

There we have it, 5 snippets in JavaScript. These snippets aim to shed light on indispensable code snippets that can transform the way we approach various challenges.

Do you have a favorite snippet? Share it with other readers by pasting it in the comments below!

Happy coding.

comments powered by Disqus

Related Posts

Routing with Angular: A Quick Tutorial

Today, we’ll be looking at the navigation and routing aspects in Angular. This tutorial is a continuation of our previous starter tutorial where we created a simple Angular application, installed Tailwind CSS, and created a navigation bar.

Read more

A 2024 Exploration into HTMX

Are you ready to discover the current game changer in web development? Meet HTMX, a groundbreaking library that changes the way you interact with web apps.

Read more

Creating a Navbar with Angular 17 and Tailwind CSS

Angular is a popular front-end framework, currently in its 17th iteration! Developed by Google and loved by many, it is currently one of the most relevant technologies one can be learning today.

Read more