Interactive URL Copy Feature in Webflow Using Clean JavaScript and Clipboard API
A Clean URL Copy Feature Using Clean JavaScript an
Because who doesn’t appreciate a great user experience?
Better than copy pasting it from the address bar!
Because with all the refers and stuff sharing URLs has become super annoying…
I had some trouble implementing an interactive URL copy feature in my Webflow projects. I like this functionality myself a lot, because sharing a link with colleagues than copy pasting it from the address bar with all the refers and stuff is super annoying.
can significantly enhance the user experience on your website, by allowing visitors to effortlessly copy the URL of your webpages and share them.
It was important for me to use clean JavaScript, meaning the code is straightforward, maintainable, and efficient. By using JavaScript, we ensure broad compatibility and easy integration with your existing Webflow site or project.
The functionality of our URL copy feature is built upon the Clipboard API, a powerful tool in the modern web development toolkit. The Clipboard API provides a way to hook into the native clipboard functionality of the user's operating system, enabling you to programmatically copy and paste text.
Why is the Clipboard API so important? Well, it streamlines the process of sharing content. Instead of manually selecting and copying a URL, your website visitors can now do so with a single click. It makes sharing easier and faster, which could lead to increased user engagement, more return visits, and wider dissemination of your content.
Script
<!-- Share with Copy-Link -->
<script>
document.getElementById("copy-link").addEventListener("click", async (event) => {
event.preventDefault();
const currentUrl = window.location.href;
if (!navigator.clipboard) {
document.getElementById("copy-status").textContent = "Your browser doesn't support Clipboard API.";
return;
}
try {
await navigator.clipboard.writeText(currentUrl);
document.getElementById("copy-status").textContent = "URL Copied!";
} catch (err) {
console.error("Failed to copy URL: ", err);
document.getElementById("copy-status").textContent = "Failed to copy URL.";
}
// Use setTimeout to clear the message after 3 seconds
setTimeout(() => {
document.getElementById("copy-status").textContent = "";
}, 3000);
});
</script>
Documentation
Script Overview
This script adds a "click" event listener to an HTML element (identified by the ID "copy-link"). When this element is clicked, the script attempts to copy the current page's URL to the clipboard using the Clipboard API. The outcome of this operation is then displayed in another HTML element (identified by the ID "copy-status"). The status message will disappear after 3 seconds.
Detailed Description
- The
document.getElementById("copy-link")
function gets the HTML element with the ID "copy-link". This should be the element that the user clicks on to copy the URL. - The
addEventListener("click", async (event) => {...}
function adds a click event listener to the "copy-link" element. When the element is clicked, the provided asynchronous function is executed. event.preventDefault();
prevents the default action associated with the click event. For example, if the "copy-link" element is a hyperlink, it would prevent the page from navigating to the hyperlink's URL.const currentUrl = window.location.href;
gets the current page's URL.- The script then checks if the
navigator.clipboard
object is available. If not, it updates the "copy-status" element to indicate that the browser does not support the Clipboard API, and then returns early to stop execution. - The script attempts to copy the current page's URL to the clipboard using
navigator.clipboard.writeText(currentUrl)
. This operation returns a Promise. - If the Promise is fulfilled (the copy operation is successful), the script updates the "copy-status" element to indicate success ("URL Copied!").
- If the Promise is rejected (the copy operation fails), the script logs the error to the console and updates the "copy-status" element to indicate failure ("Failed to copy URL.").
- Regardless of whether the operation was successful or not, the script uses
setTimeout
to clear the "copy-status" element's text after a delay of 3 seconds.
HTML Elements Required
This script requires two HTML elements:
- An element with the ID "copy-link". This is the element that the user clicks on to copy the current page's URL. It can be any type of element, but it's typically a button or a hyperlink.
- An element with the ID "copy-status". This is the element where the script displays the outcome of the copy operation. It can be any type of element that can contain text, such as a
p
ordiv
element.
Errors and Debugging
If the script fails to copy the URL or fails to update the status message, make sure that:
- The "copy-link" and "copy-status" elements exist in the HTML and are not being removed or having their IDs changed dynamically by other JavaScript code.
- The Clipboard API is available in your browser and context. Some older browsers do not support the Clipboard API, and even some modern browsers only support it in secure contexts (HTTPS).
- Your HTML and script are loaded in the correct order. If the script runs before the HTML elements it references are loaded, it will not work correctly.
Optimize Netlify Build Minutes and DecapCMS by Skipping Unnecessary Builds
Optimize Netlify Build Minutes and DecapCMS by Skipping Unnecessary Builds
Displaying Both the Publication and Update Dates on Webpages
Showing both the update and the publish date on your blog / web page seems to be difficult for Search Engines and therefore it seems like only displaying “last updated” is the safer way. If your blog shows more than one date, you are probably confusing Google.
Localization: The "hreflang" Tag Accross Different Domains
John Mueller on how to use the hreflang tags across domains for the localization schemas: It doesn't matter if it's all on one domain or across multiple domains. It should just be one clear place per country and language.
DecapCMS Markdown Guide: Handling URLs with Parentheses for Text Fragment Highlighting
Are broken links in your DecapCMS Markdown articles giving you a headache? never let parentheses break your links again: handle text fragment highlighting in Markdown. No more parentheses-induced troubles in your Github articles built with Netlify!
Leveraging a Small JavaScript for a Quick Multilingual Strategy in Webflow
A button that appears when there is an alternate language defined for your content, making your cotent more relevant to your users experiences. Implementing a Dynamic Language Switcher Button with JavaScript
Interactive URL Copy Feature in Webflow Using Clean JavaScript and Clipboard API
An interactive URL copy feature in Webflow. Using clean JavaScript and the powerful Clipboard API, making it easier for visitors to share your pages. Because who doesn’t appreciate a great user experience?
An Extensive Dynamic Table of Contents Generator for Webflow CMS
Boost your Webflow Blog's readability and SEO with a dynamic Table of Contents (ToC) generator. It automatically creates a stylable, navigable ToC from your headings, and enhances user experience by highlighting the active section during scrolling.
Styling Our Auto-Generated ToC in Webflow
Creating or Changing Slugs in DecapCMS (formerly Netlify CMS)
Changing the URL Slug of your post in DecapCMS in config.yaml using the slug key and name key
Smooth Scrolling to the Next Section with JavaScript and [foo](#next) markdown syntax
When I write [[`foo`](#next)`](#next)` markdown syntax in my content I want the reader to jump to the next section, the next anchor, on my webpage.
Vimeo vs YouTube Embed for your Website
Consider this when you decide between YouTube or Vimeo for Website embeds
Editorial Workflow in Decap CMs (formerly Netlify CMS)
README for ChatGPT and How to Write the Best Prompts
When answering prompts, does it help ChatGPT to be more specific and precise if you give it a set of definitions upfront?
Use Hash-symbol vs Triple-quotes Syntax for Commenting Python Code
Consider this when you choose the syntax for commenting code in Python
Dynamically Generated ToC with Webflow CMS
Generating ToC’s based on h2 and h3 headings of a rich text CMS element with active states in a sticky Table of Contents
Dynamic Social Media Share Buttons for Webflow CMS Blogposts
Add a Twitter button and a share on LinkedIn to your blogposts with sharing content generated from Webflow CMS
Calculate Read Time from Webflow CMS
Calculated a read time from Webflow CMS and add to your blog template.
Add Copy-able Code Blocks to Webflow CMS
Uses highlight.js and custom code to add code blocks where you can copy the code to rich text element of Webflow CMS