Start a free Courses trial
to watch this video
Ever wondered how a Copy to Clipboard button works? Theyโre all over the web. In this quick guide, Dustin demonstrates how to add this feature to an input field with ease by writing just a few lines of JavaScript! *Correction: at 1:18 the keyboard shortcut for Paste on a Mac should be Command + V. Control + V on Windows.
Related Course
Resources
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up[MUSIC] 0:00 Hey, what's up? 0:01 My name is Dustin. 0:05 And I'm a developer here at Treehouse. 0:06 How often have you seen a Copy to Clipboard button while you're on the web? 0:08 They're all over the place. 0:12 And they're actually really easy to create with just a little bit of JavaScript. 0:13 So let me show you how we can build one. 0:17 Let's take a look at the HTML. We basically just have a container for our input and 0:19 inside of it we just have an input the type of text and a button. 0:24 The magic is actually going to be in the JavaScript so let's create a couple of 0:29 variables. I'll right const input = document.querySelector 0:33 And we'll select the input and I'll do the same for 0:37 the button I'll write const btn = document.querySelector('button'). 0:40 And what we'll do is we'll run an event listener on the button by writing 0:45 button.addEventListener(), and we want to listen for clicks. 0:48 Inside the callback function, we'll just write navigator.clipboard.writeText(). 0:52 And write text is a method that takes in one argument, 0:59 which is the text that we want to copy. 1:02 So in this case, we want to copy the input.value. 1:04 I'll hit Save and head on over to my browser. 1:08 I'll type in hello world into the input and I'll hit our copy button and 1:10 now our text is copied. 1:14 I'll open up our console and I'll press Command V on my keyboard and 1:16 now you see Hello World pasted into the console. 1:20 Now I'll erase Hello World and I'll type in Team Treehouse. 1:23 I'll hit the copy button again and paste our clipboard into the console and 1:27 now you see Team Treehouse. 1:30 Sweet, it works! 1:32 And that's it. 1:34 It really doesn't take a whole lot of code to write a copy to clipboard feature using 1:35 JavaScript. 1:38 This was just one demonstration of one solution but 1:39 if you'd like to learn more about Clipboard or Navigator, 1:42 check out the description or teacher's notes down below for more resources. 1:45 I hope this quick guide helped and I'll see you in the next one. 1:48 Until then, have fun and happy coding! 1:51
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up