kamp
kamp

Reputation: 15

Copy to clipboard with disappearing message

I want to add a feature to my copy to clipboard function so that it shows "copied!" message when user clicks, with fade in effect and disappears after 5 seconds. I built the following code, it works find until it fades out the entire box! I don't understand what I'm doing wrong here.

    $(".copyto-clipboard .copyto-clipboard-text").click(function(event){
        var $tempElement = $("<input>");
        $("body").append($tempElement);
        $tempElement.val($(this).closest(".copyto-clipboard").find("span").text()).select();
        document.execCommand("Copy");
        $tempElement.remove();
        $('.copyto-clipboard').append('<span class="copied">copied!</span>').fadeIn(100).fadeOut(500);
    });

Upvotes: 1

Views: 1758

Answers (2)

Kida
Kida

Reputation: 840

I made some improvements to @NawedKhan code:

    var $copiedElement = $("<small style='position: absolute;z-index: 10;' class='badge badge-success'>");

    if($('#idCopy').length === 0)
    {
        $copiedElement.addClass('copied').text('copied');
        $(this).append("<span id='idCopy' style='position:relative;top: -0.5rem;left: -0.2rem;'>");
        $('#idCopy').append($copiedElement);
        $('#idCopy').fadeIn(100);
        $('#idCopy').fadeOut(1000, function() { $(this).remove(); }); 
    }

position: absolute; with relative parent (place message anywhere you want without updating the flow of other objects on the site

if($('#idCopy').length === 0) (don't add a new message, if the old one still exists)

$(this).remove(); (remove old hidden messages)

Upvotes: 0

Nawed Khan
Nawed Khan

Reputation: 4401

Because you are fading out the whole div, not the span you just added. Secondly fadeout(500) is not 5 seconds. The number is in milliseconds therefore 5000 is 5 seconds.

Change your code as following to apply the fade in and fade out on the newly created span:

var $copiedElement = $("<span>");
$copiedElement.addClass('copied').text('copied!');
$('.copyto-clipboard').append($copiedElement);
$copiedElement.fadeIn(100);
$copiedElement.fadeOut(5000);

Upvotes: 1

Related Questions