Quickie Dev #10: Some util JS tools & code snippets

Fancy a few pure JavaScript code snippets and useful tools? 🙂

This article is also available on Medium.

Photo by Clément Hélardot on Unsplash

Today, I thought I’d share some of the JS code and tricks I’ve accumulated over the years throughout my web projects. These examples are pretty various – hopefully, some might be of use for you!

Snippet #1: Copying some text to your clipboard

You might have already seen this in various websites: it’s oftentimes useful to have a little “copy” button next to text input fields – for example an input showing a temporary password, or a unique reference code.

But how do you get some value in your document and send it to the clipboard of the user? Here is a little snippet to do that:

If you open this HTML page, enter some text and click the button, you’ll then have the contents of your input in your clipboard and you’ll be able to paste it wherever you want! 🙂

The idea in this snippet is to use the built execCommand() method to copy the value of a DOM element to the clipboard (this feature is supported by most browsers since ~April 2015).

Be careful, though: you need an actual document node to select so that the command can extract the value from somewhere. So if you don’t have a real DOM input or text area, you should create a fake one (using document.createElement() as discussed in a previous tutorial I wrote on manipulating DOM via pure JS) that is hidden and is immediately destroyed after the copy is done.

Snippets #2 and #3: Fetching info from an API (with XHR or fetch())

It’s pretty common for your client-side JS to have to communicate with some API. It can be your own API or a third-party API, but in any case you’d like to fetch some data from a given endpoint and bring it back into your client code.

To do this, there are two possible techniques: you can either create a basic XML HTTP Request (or “XHR” in short), or you can use the fetch() API.

  • XML HTTP Requests are built-in browser objects that let you get some content from a given URL in a synchronous or an asynchronous way. We use the async version most of the time, and that’s what I’ll show here.

To create, execute and eventually retrieve data via an XHR, you have to follow several steps.

  1. First, you create the request by open()ing it on your URL.
  2. Then, you need to define various functions on it: those functions are callbacks that will be executed at crucial points during the lifetime of the request, like onload, onerror or onprogress (note that not all of those callbacks are mandatory). In particular, you want to post-process the data you received from the given URL in the onload method.
  3. Once your request is ready to react properly to those events, you can send() it.

Here is an example of how to call the free Game of Thrones Character API (just click on the button and it will fill in a <pre> block with the results in a nicely JSON-formatted way):

  • However, there is now a more modern tool for getting data from a URL: using the fetch() API. It’s an easy-to-use feature to retrieve info asynchronously. It is usually much easier to configure than the XHR alternative 😉

Snippet #4: Sleeping for X seconds

If you want to pause the execution of your script for a given amount of seconds, then you can use this little function to wait and hold (here I show how to call it either in a normal or an async function):

If you execute this script, you’ll see that the “Hello world!” is set to the first <div> right away when you click any of the buttons, but the second text is only updated after 2 seconds 🙂 (Also, clicking the buttons clears the second text at the beginning so you can retry several times and test the two properly)

A useful tool: the debugger

JavaScript is known for being a bit light on debugs and error messages. More often than not, when you’re working with vanilla HTML and JS, if you have a mistake somewhere in your code, you’ll just have a blank page and a vague message in the console.

Ah, how many times have you wished you could just have stopped your JS code during its execution to peek at the path it takes! Right? Well – you can actually do just that using the debugger; command 🙂

This JS keyword lets you place “false” breakpoints in your code (I say “false” because they’re not actual breakpoints, but they work exactly the same!). When you then execute the script with your browser dev tools open, it will stop as soon as it hits one of these “breakpoints” and show you its current state in the “Sources” tab (for Chromium-based browsers) or “Debugger” tab (for the Firefox browser):

You can then go through the execution of your code with more granularity (for example, line by line, or function by function). And you can see that the debugger also gives you a peek at the current scope you’re working in – in other words, which variables you currently have defined, what values they have, etc.

This is really handy for identifying the flaws in your code quickly and while focusing on the proper parts of the code!

Note: beside the browsers, nice IDEs like VS Code also have embedded debuggers that let you examine the execution path and scopes easily like this 😉

Conclusion

What about you: do you have any tool or JS routines you’d like to share? Feel free to react in the comments! 😉

2 thoughts on “Quickie Dev #10: Some util JS tools & code snippets”

  1. Hello this is kind of of off topic but I was wondering if blogs use WYSIWYG editors or if you have to
    manually code with HTML. I’m starting a blog soon but have no coding skills so
    I wanted to get guidance from someone with experience.
    Any help would be enormously appreciated!

Leave a Reply

Your email address will not be published. Required fields are marked *