6 JavaScript Snippets to Polish Your Site


JavaScript is a popular language, and it’s easy to find general-purpose snippets that help complement it. But its most important context is the web browser, and there’s a lot you can do to enhance your web pages with just a little JavaScript.

These snippets are designed to be dropped into any website, regardless of its underlying framework or structure. They are all short—many are one-liners—and offer plenty of bang for their buck.

Try opening a Google search results page and pressing the / key. You should notice that the search box automatically focuses, letting you quickly type another search. This shortcut is so useful that many other sites have followed suit, from YouTube to MDN.

You can get the same effect on your own site with minimal effort. Take a search box that looks something like this:

        <input type="text" id="search" />

With just a line of JavaScript, you can add this helpful keyboard shortcut:

        document.addEventListener("keyup", function (e) {
    if (e.key === "https://www.howtogeek.com/") {
        document.getElementById("search").focus();
    }
});

The event listener checks for the forward slash key. If pressed, it obtains the search box element using getElementById(), then calls its focus() method to activate the search box and place the cursor inside it.

Related


I Became a Master of Google Chrome After Memorizing These Shortcuts

Try these Chrome shortcuts once, and you’ll be a fan for life.

Note that, using this particular code, the focus action is non-destructive. Be careful if you make any changes! For example, using the keydown event instead of keyup would focus the element before the browser handles the key press, so a “https://www.howtogeek.com/” would end up in your search box.

2

Automatic Fragment Identifiers

Fragment identifiers are a useful way of linking to a specific point on a webpage. If an element has an id attribute with a value “example,” then a link ending “#example” will automatically scroll to that point in the page.

If you’re publishing content online, using id attributes will encourage people to link to it. It can be tricky to remember to include ids, but injecting them dynamically gets around this problem.

        document.querySelectorAll("h2").forEach(function(el) {
    if (!el.hasAttribute("id")) {
        el.setAttribute("id", el.textContent.replaceAll(/[^a-z]/gi, ''));
    }
});

This snippet loops over each h2 element on your page. If it doesn’t already have an id attribute, the code sets one, based on the text inside the heading. You may have noticed that this is the same kind of technique that sites like Wikipedia use for heading ids.

Note the regular expression replacement that removes all characters that aren’t letters (a-z). If you publish in a language other than English, or you use headers that may repeat, you should consider tweaking the regular expression.

Related


How Do You Actually Use Regex?

Regex, short for regular expression, is often used in programming languages for matching patterns in strings, find and replace, input validation, and reformatting text.

3

Rewrite the URL as Canonical

Have you ever had to deal with URLs that include things like ?utm_content=buffercf3b2&utm_medium=social or #:~:text=search? These parameters can be added by analytics scripts and search engines, even if your site doesn’t make any use of them. Although they shouldn’t concern your visitors, they can make your own analytics tracking more difficult, and you probably don’t want people using those URLs in any links.

Related


What Is A URL (Uniform Resource Locator)?

When you type an address into your web browser, a lot of things happen behind the scenes.

Here’s a tiny piece of JavaScript that will help clean up your URLs:

        window.history.replaceState(null, "",
    document.querySelector("link[rel=canonical]").getAttribute("href")
);

The History API is a powerful way of managing browser history, including the current page. It lets you manipulate the URL without causing a page refresh.

In this case, the replaceState() method does the work. Note how we call it with falsey values for the first two arguments because it’s only the third we care about; it represents a replacement URL.

This snippet assumes you already have a canonical URL element in your markup, like this:

        <link rel="canonical" href="https://example.org/this-is-just/an-example" />

It’s a good idea to include a canonical link because search engines typically use it to formulate their results. If you’re not always using it, though, make sure to add a conditional check to this snippet.

There are several ways you can open a link in a new tab in your browser. As a publisher, though, you may want to enforce this. In particular, it’s recommended that you open resources like PDFs in a separate tab, since they have a very different context to normal web pages.

You may even go so far as to open all external links in a separate tab. The best way of doing this is by editing your HTML and adding the target attribute:

        <a href="https://example.org" target="_blank">
   An example link that will open in a new tab
a>

If you haven’t already done so, however, this can be a lot of work. Consider the following approach, which transforms links dynamically using JavaScript:

        document.querySelectorAll("a").forEach(function(node) {
    var url = new URL(node.getAttribute("href"), window.location);

    if (window.location.origin != url.origin) {
        node.setAttribute("target", "_blank");
    }
});

This code compares window.location.origin—your website’s domain—with url.origin, which is the domain of each link. This means the approach will work even if you use full absolute URLs when linking to your own site.

The big advantage here is that you can quickly update all links if you ever decide to change this behavior. For example, you can drop the condition and have all links open in a new tab. Or you can drop this code altogether and keep all links in the same tab.

One of the most convenient keyboard shortcuts when browsing the web is the Tab key. Press this, and you’ll move to the next link in the page. Hold down shift and you’ll move to the previous link. With this simple system, navigating pages with the keyboard is much easier.

There’s a downside, though: instantly jumping to a different part of the page can be jarring and leave you feeling disorientated, especially when links are far apart, across several screens. This snippet helps by smoothing the experience.

        document.addEventListener("keyup", function (e) {
    if (e.which === 9) {
        e.target.scrollIntoView({
            behavior: "smooth",
            block: "center",
        });
    }
});

This event handler runs when a key has been released, checking the which property of the event to test for the Tab key. At this point, the browser will have already moved focus to the next link, so e.target will represent the link the user has just navigated to.

The scrollIntoView method then does all the work. The options ensure links are scrolled to a vertically central position, with a smooth animation.

6

Page Scroll Progress

Since browsers and operating systems have made scroll bars less visible, some sites have taken on the burden themselves. A progress bar that shows how far you’ve scrolled through a page is now a familiar sight. It takes a bit of work to add one to any page, but not much:

        let p = document.body.appendChild(
        document.createElement("progress"),
    ),
    de = document.documentElement;

p.setAttribute("value", "0");

p.setAttribute(
    "style",
    "position: fixed; top: 10px; left: 10px; right: 10px; width: auto;",
);

document.addEventListener("scroll", function () {
    p.value = de.scrollTop / (de.scrollHeight - de.clientHeight);
});

Most of the work here involves setting up the progress bar element, which looks like this:

        <progress
   value="0"
    style="position: fixed; top: 10px; left: 10px; right: 10px; width: auto;"
>progress>

This style ensures that the progress bar is always visible, at the top of the window. The rest of the script handles the document’s scroll event and sets the progress value between 0 and 1, which is the default range. The scrollTop, scrollHeight, and clientHeight properties measure the scroll position, total height, and visible height respectively.

Related


How to Always Show Scrollbars in Windows 11

To scroll or not to scroll, that is the question.

By admin

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *