Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set `innerText` with fade-in effect?

Say you have a button to replace paragraphs within the same area, same page.

Can you make every switch, via setting innerText or textContent, fade in every time?

I now use keyframes to change its opacity from 0 to 1, but it only works for the first paragraph after the page is loaded. After that, whenever I replace the text with innerText, the effect doesn't show at all.

All the text waiting in line is hard coded in JavaScript, not in HTML - if it makes a change.

like image 341
Jason Lam Avatar asked Nov 27 '15 08:11

Jason Lam


2 Answers

You will need to either introduce a delay or a repaint. Introducing a delay is probably the easiest.

p.classList.add('hide');               // add the class
setTimeout(function() {                // delay and 
    p.textContent = txtList[idx];      // change text
    idx = (idx + 1) % txtList.length;
}, 500);
setTimeout(function() {                // delay and 
    p.classList.remove('hide')         // remove the class
}, 500);

Fiddle: http://jsfiddle.net/abhitalks/rdnt9d5w/

Snippet:

var txtList = [
    'Lorem', 'ipsum', 'dolor', 'sit', 'amet', 
    'Lorem ipsum dolor sit amet'
], idx = 0, 
   p = document.getElementById('p1');

document.getElementById('btn1').addEventListener('click', fadein);

function fadein() {
    p.classList.add('hide');
    setTimeout(function() { 
        p.textContent = txtList[idx];
        idx = (idx + 1) % txtList.length;
    }, 500);
    setTimeout(function() { 
        p.classList.remove('hide')
    }, 500);
}
p { opacity: 1; transition: all 0.5s; }
p.hide { opacity: 0; }
<p id="p1">Lorem ipsum dolor sit amet</p>
<hr />
<button id="btn1">Change</button>
like image 163
Abhitalks Avatar answered Oct 06 '22 00:10

Abhitalks


I would do it something like this:

var i = 0;
var strings = ['first string........', 'second string.........', 'third string..........', 'fourth string...............'];
$('#add-text').click(function () {

    if (i > strings.length - 1) i = 0;

    var $result = $('#result');
    $result.fadeOut("fast", function () {
        $result.text(strings[i]).delay(300).fadeIn('slow');
        i++;
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add-text">Add Text</button><br>
<p id="result">Here is some default text....</p>
like image 22
Wesley Smith Avatar answered Oct 06 '22 01:10

Wesley Smith