Copy Something with JavaScript

Hi everyone. In this article, I’ll tell you how to copy something with the JavaScript.
Before starting, I need to say that, there is an npm package that built with the information in this article.
You can install it to test
npm i copy-simple
I will create an empty function called copy. We will use this function to copy values, element text, html or selected texts.
The el argument will use to handle element by the querySelector method. Which means, our method will be changed.
There are new methods which contain nothing. But our method will look like that. As you see, our method will return an object that contains methods.
Creating Temporary HTML Element To Copy
In order to copy something, we need to create an input element. Probably there are different ways to do that. But after copy the value, we will remove this element. In order to do this, we will use the saveClipBoard method.
Creating the saveClipBoard Method
Our method will be like this;
In this method, we assigned the data argument’s value to the dummy element’s value. After that, we used the execCommand method. This method will return a boolean value. After this method, we will remove the dummy element. You can even try if it like this.
Getting Values
The other methods will be like this
These methods can understand easily. Every method calls the saveClipBoard method. There is a different method called getSelection, you may don’t know it. Mozilla says that;
Returns a Selection object representing the range of text selected by the user or the current position of the caret.
That’s all. Our method completed.
Let’s test it
I’ve created a pen on the CodePen for you. In order to test our method you need to click to the button.
You can use the other methods which in the comment blocks.
I hope this article will help you.
Thanks for reading.