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.
Related Posts
The Great JavaScript Debate: To Semicolon or Not?
Since I’ve started learning this language, JavaScript has undergone some heavy changes. Most notably, it seems to be the norm to not use semicolons anymore.
Read moreHacktoberfest 2024: Get a Free JavaScript Today Sticker
October is here, and that means one thing in the tech world—Hacktoberfest! This annual event, powered by DigitalOcean, Cloudflare, Quira, and other sponsors, encourages developers of all skill levels to contribute to open-source projects.
Read moreCreating a Real Time Chat Application with React, Node, and TailwindCSS
In this tutorial, we will show you how to build a real-time chat application using React and Vite,as well as a simple Node backend.
Read more