😵UX of your website can be affected by this event.

Photo by Headway on Unsplash

😵UX of your website can be affected by this event.

Enhance User experience of your website with this clipboard event

In the end, it's all about the user experience. It's not just the design that makes difference. Events can also add a huge impact on the user's experience.

Here is a small javascript event that can be triggered and used purposefully.

Whenever a user tries copying some text from the website, before pasting it somewhere it goes to the clipboard and stays there temporarily. A copy event of javascript can be used to tweak this data in the clipboard.

The example use case for this event is -

On an article website whenever the content is copied, on an advertisement basis text such as "Read More on xyz.com" can be added to the clipboard data. (code implementation is given below).


Copy Event

You can find more creative ways to use this event, now let's dive into the implementation.

Copy events fire whenever the user does a copy on the browser interface.

The handler for this event can modify the data of the clipboard by the command setData(format, data) by calling it on the event property ClipboardEvent.clipboardData and then preventing the default event by event.preventDefault()

NOTE: The handler cannot read the clipboard data it can only add data.

use copy event on addEventListner command or set the event handler property.

addEventListener('copy', (event) => { });

oncopy = (event) => { };

Here is a sample HTML code from which text is copied

<div class="articleContent" contenteditable="true">This content is a sample text to display the copy event of browser </div>
<div class="pastePoint" contenteditable="true"> here you can paste the content </div>
const articleContent = document.querySelector('div.articleContent');

articleContent.addEventListener('copy', (event) => {
    const selection = document.getSelection();
    event.clipboardData.setData('text/plain', "Read More on https://www.xyz.com");
    event.preventDefault();
});

Through this event, you can create a nice user experience for your website ✨

You can read about it on MDN Docs.

You can experience the implementation on code pen.

👀See you in my next blog, till then take care and keep 🧑‍💻 developing.