copy text to clipboard js


in this article, i will show you clipboard js. copying text to the clipboard shouldn't be hard. It shouldn't require dozens of steps to configure or hundreds of kbs to load. but most of all, it shouldn't depend on flash or any bloated framework

example:

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.10/clipboard.min.js"></script></head>
<body>
    <input class="form-control" type="text" id="txtval">
    <br>
    <button class="btn btn-primary" data-clipboard-target="#txtval">click here</button>
    <script>
        $('button').tooltip({
            trigger: 'click',
            placement: 'bottom'
        });
        function setTooltip(message) {
            $('button').tooltip('hide')
                .attr('data-original-title', message)
                .tooltip('show');
        }
        function hideTooltip() {
            setTimeout(function() {
                $('button').tooltip('hide');
            }, 1000);
        }
        //clipboard
        var clipboard = new Clipboard('button');
        clipboard.on('success', function(e) {
            setTooltip('Copied!');
            hideTooltip();
        });
        clipboard.on('error', function(e) {
            setTooltip('Failed!');
            hideTooltip();
        });
    </script>
</body>
</html>

Post a Comment

0 Comments