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

Solving a Common Interview Question: the Two Sum Algorithm in JavaScript

Imagine you’re at a lively party, and everyone is carrying a specific number on their back. The host announces a game – find two people whose numbers add up to the magic number, and you win a prize!

Read more

Remove Duplicates from Arrays and Strings in JavaScript

Removing duplicates is a common problem in programming that can arise in various contexts, such as cleaning up data or ensuring unique entries.

Read more

Remote First: 5 Websites for Remote Job Opportunities

Would you prefer to work in an office, or while sitting at a beach somewhere in Thailand (i.e. remotely)? Okay, maybe there’s no beach in this scenario, but there’s definitely silence, and maybe your cat.

Read more