5 Useful JavaScript Snippets You Should Know About
Javascript Tutorial

5 Useful JavaScript Snippets You Should Know About

1 min read

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.

About the Author

Matt Fay

Matt Fay

Matt is the founder of JavaScript Today, a platform dedicated to high-quality JavaScript education and commentary. With a deep curiosity for technology, he gravitates toward understanding how things work and has been diving into the world of information security. Outside of coding, Matt enjoys exploring languages; he can understand some Russian and Italian, and is currently learning Thai.

Learn AI Skills with Codecademy (729x90)

Discussion (Loading...)

Join the conversation

Join the Discussion

Sign in to share your thoughts and engage with the JavaScript Today community.

Loading comments...

Related Articles

Continue your learning journey with these related posts

Never Miss a JavaScript Update

Join our community of developers and receive insightful articles and coding tips every week.