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

Unveiling the Fascination of the Collatz Conjecture: Exploring Sequence Creation with JavaScript

The Collatz Conjecture, also known as the 3x+1 problem, is a fascinating mathematical puzzle that has intrigued mathematicians for decades. It has sparked publications with titles such as The Simplest Math Problem Could Be Unsolvable, or The Simple Math Problem We Still Can’t Solve because it is, indeed, rather simple-looking.

Read more

The Art of Data Visualization: Exploring D3.js

Data is everywhere, flowing into our applications from various sources at an unprecedented rate. However, raw data alone holds little value unless it can be transformed into meaningful insights.

Read more

JavaScript’s Secret Weapon: Supercharge Your Web Apps with Web Workers

During an interview, I was asked how we could make JavaScript multi-threaded. I was stumped, and admitted I didn’t know… JavaScript is a single-threaded language.

Read more