.

HD Mp4 3gp Video
Live Update Video
Play/Download
Live 3D App
Search.Pencarian Menu

Add text send email to rh3252705.adda@blogger.com or Click this (Text porn Will delete) | Tambah teks kirim email ke rh3252705.adda@blogger.com atau Klik ini (Teks porno akan dihapus)
Total pos : 19157+

[Go Make Things] How to build a copy-to-clipboard HTML Web Component

Need front-end help but don't need a full-time employee? I now offer subscription front-end engineering. Ship faster and build better systems. Pause or cancel any time.

Yesterday, we looked at how to copy items to a user's clipboard with JavaScriprt. Today, we're going to turn that into an HTML Web Component.

Let's dig in!

The Custom Element

For this Web Component, let's use a <copy-to-clipboard> element.

<copy-to-clipboard>  </copy-to-clipboard>

With the HTML Web Component approach, we start with HTML and enhance it rather than rendering all the things with JavaScript.

Let's add a <button> with our desired text inside the custom element.

<copy-to-clipboard>  	<button>Copy Me</button>  </copy-to-clipboard>

Options & settings

One of the nice things about Web Components in general is that you can define all sorts of options for them directly on the element as attributes.

We'll add an attribute for the [text] to copy.

<copy-to-clipboard text="Sample">  	<button>Copy Me</button>  </copy-to-clipboard>

We should also temporarily change the text of the button so the user knows the text was copied.

And since screen readers don't always announce changes to button text, we'll also have a visually hidden status element for screen readers. Let's also define properties for the text to use for both of them: [copied-btn] and [copied-msg], respectively.

<copy-to-clipboard  	text="Sample"  	copied-msg="Copied the URL"  	copied-btn="Copied!"  >  	<button>Copy Me</button>  </copy-to-clipboard>

Defining our Web Component

Next, let's define our Web Component in our JavaScript.

We'll use the customElements.define() method, passing in the name of our custom element and a class that extends the HTMLElement class.

Inside it, we'll run our constructor() method, and run the super() function to get access to the parent HTMLElement class properties and methods.

customElements.define('copy-to-clipboard', class extends HTMLElement {    	/**  	 * The class constructor object  	 */  	constructor () {    		// Gives element access to the parent class properties  		super();    	}    });  

Setting up the Web Component

Inside the constructor(), we'll use the Element.querySelector() method to get the button element and assign it to a property.

We'll use the Element.getAttribute() method to get our options and settings. We'll also cache the original button text so we can change it temporarily after copying the text, and then reset it again a few seconds later.

If there's no this.text to copy, we'll use the return function to bail early.

constructor () {    	// Gives element access to the parent class properties  	super();    	// Get the button  	this.btn = this.querySelector('button');    	// Get the text or target  	this.text = this.getAttribute('text');    	// Get the messages  	this.original = this.btn.innerHTML;  	this.copiedMsg = this.getAttribute('copied-msg') ?? 'Copied to Clipboard';  	this.copiedBtn = this.getAttribute('copied-btn') ?? 'Copied!';    	// If there's no text to copy, bail  	if (!this.text) return;    }  

Next, we'll start listening to click events on this.btn.

We're going to use the handlEvent() method for managing our events.

constructor () {    	// ...    	// If there's no text to copy, bail  	if (!this.text) return;    	// Listen for clicks  	this.btn.addEventListener('click', this);    }  

Next, we'll create a div and add a role of status. We'll use this to make announcements for screen readers.

We're going to save this as a property of component so that we can access it later. Then, we'll append() it inside our Web Component.

constructor () {    	// ...    	// Listen for clicks  	this.btn.addEventListener('click', this);    	// Add an alert  	this.notify = document.createElement('div');  	this.notify.setAttribute('role', 'status');  	this.append(this.notify);    }  

Copying to the clipboard

Let's pull in the copyToClipboard() method we wrote yesterday as a class method.

We have access to this.text as a class property, so we can remove the argument and pass this.text into the writeText() method instead.

/**   * Copy text to the user's clipboard   */  async copyToClipboard () {  	try {    		// Copy the text  		await navigator.clipboard.writeText(this.text);    	} catch (error) {  		console.warn('Unable to copy.', error);  	}  }  

After copying the text, let's update the this.btn HTML to our this.copiedBtn property.

We'll also set the Element.textContent on our this.notify element to the this.copiedMsg property, to announce our change to screen readers.

async copyToClipboard () {  	try {    		// Copy the text  		await navigator.clipboard.writeText(this.text);    		// Update the button and status text  		this.btn.innerHTML = this.copiedBtn;  		this.notify.textContent = this.copiedMsg;    	} catch (error) {  		console.warn('Unable to copy.', error);  	}  }  

We don't want these changes permanently.

We'll use the setTimeout() method to reverse them 5 seconds (5000 ms) later.

async copyToClipboard () {  	try {    		// Copy the text  		await navigator.clipboard.writeText(this.text);    		// Update the button and status text  		this.btn.innerHTML = this.copiedBtn;  		this.notify.textContent = this.copiedMsg;    		// Reset after 5 seconds  		setTimeout(() => {  			this.btn.innerHTML = this.original;  			this.notify.textContent = '';  		}, 5000);    	} catch (error) {  		console.warn('Unable to copy.', error);  	}  }  

Our handleEvent() method runs whenever a click happens. Inside it, we'll run our this.copyToClipboard() method.

/**   * Handle events on the Web Component   * @param  {Event} event The event object   */  handleEvent () {  	this.copyToClipboard();  }  

Styling and profiling!

Ok, no profiling. Just styling.

First, our <copy-to-clipboard> element is useless without JavaScript. Let's hide it until the JS has defined it.

copy-to-clipboard:not(:defined) {  	display: none;  }

We also don't necessarily want the [role="status"] element displayed visually, since the button text also changes.

Let's hide it visually while also keeping it accessible to screen readers

/**   * Visually hide an element, but leave it available for screen readers   * @link https://github.com/h5bp/html5-boilerplate/blob/master/dist/css/main.css   * @link http://snook.ca/archives/html_and_css/hiding-content-for-accessibility   */  copy-to-clipboard [role="status"] {  	border: 0;  	clip: rect(0 0 0 0);  	height: 1px;  	margin: -1px;  	overflow: hidden;  	padding: 0;  	position: absolute;  	white-space: nowrap;  	width: 1px;  }

Putting it all together

Now, we've got a completed Web Component.

You can see it in action and try it yourself here on CodePen.

Learn more about subscription front-end engineering. Ship faster and build better systems.

Cheers,
Chris

Want to share this with others or read it later? View it in a browser.

Share :

Facebook Twitter Google+ Lintasme

Related Post:

0 Komentar untuk "[Go Make Things] How to build a copy-to-clipboard HTML Web Component"

Back To Top