In the digital age, users use various online applications and platforms, and improving user experience has become important. One of the wishes is to be able to easily Copy Selected Text to Clipboard with jQuery. This feature not only simplifies the user’s tasks but also improves overall usability.
Importance Of User Experience
In order for any program or website to succeed, user experience, or UX, is essential. Giving customers easy-to-use features—like the ability to copy text selections with little effort—improves their experience and promotes continuous interaction.
Simplifying Tasks for Users
Allowing users to copy content directly from a webpage allows developers to reduce steps and streamline workflows. This ease of use can greatly increase user productivity and enhance the surfing experience.
Introduction To jQuery
jQuery is a fast, small, and feature-rich JavaScript library designed to simplify client-side scripting. It provides an easy-to-use API that abstracts away many complex tasks, making it ideal for tasks like DOM manipulation, event handling, and animation.
User-Select in CSS
User-select is a CSS property that controls whether the user can select text within an element. It allows developers to specify whether text selection is allowed, prevented, or limited to specific elements on a webpage.
selector{
user-select: all !important;
}
Copy Selected Text to Clipboard with jQuery
First of all you have to make sure you already have the jQuery Library added to your website. If your site does not have jQuery library, add it first in head section of your site.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Now the main jQuery code, copy and paste it after the jQuery library:
jQuery.fn.selectText = function () {
this.find("input").each(function () {
if ($(this).prev().length == 0 || !$(this).prev().hasClass("p_copy")) {
$('<p class="p_copy" style="position: absolute; z-index: -1;"></p>').insertBefore($(this));
}
$(this).prev().html($(this).val());
});
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
document.execCommand("copy");
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("copy");
}
};
$("pre, code").on("click", function (e) {
var selector = $(this);
$(selector).selectText();
e.preventDefault();
alert("Your Text is successfully copied to clipboard");
});
Conclusion
In conclusion, jQuery simplifies the process of copying selected text to the clipboard, enhancing user experience and improving usability. By following best practices and leveraging jQuery’s cross-browser compatibility, developers can implement this functionality efficiently and reliably.