1

I've written some js to the word displaying in #changingword loops through several different words. It mostly works however when it first loads it skips through the second word so it goes from 'design' straight to 'e-commerce solutions', without showing the 'development'. After the first loop it works correctly. My code is below.

The html:

 <div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
    <h1>Creative Development</h1>
    <h2 id="changingword">Design</h2>
  </div>

The JS:

<script>
(function(){
    var words = [
        'Development',
        'E-commerce Solutions',
        'Optimisation',
        'Support',
        'Design'
        ], i = 0;
    setInterval(function(){
        $('#changingword').fadeOut(function(){
            $(this).html(words[i=(i+1)%words.length]).fadeIn("slow");
        });
    }, 1500);

})();
</script>

Any ideas why this is happening?

MariaL
  • 1,112
  • 2
  • 16
  • 41
  • Replace your `i=(i+1)` with `i++`. – NuelG Dec 06 '17 at 11:53
  • Don't replace (i+1) with i++, use ++i and you have to adjust initializing i. Check my post for more info how to use it correctly and what is the difference between prefix and postfix. – DanteTheSmith Dec 06 '17 at 12:01

3 Answers3

3

The problem is in here:

$('#changingword').fadeOut(function(){
    $(this).html(words[i=(i+1)%words.length]).fadeIn("slow");
});

You're updating i, then using the resulting value in the calculation.

Update i after using it:

$('#changingword').fadeOut(function(){
    $(this).html(words[i%words.length]).fadeIn("slow");
    i++;
});
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
0

I think the issue is that on first pass through the words[i=(i+1)%words.length] will be equivalent to words[1] not words[0].

You can increment but return the preincremented value by doing

$('#changingword').fadeOut(function(){
            $(this).html(words[i++%words.length]).fadeIn("slow");
        });
RobPethi
  • 551
  • 9
  • 27
0

It can be tricky to do increment and use result in the same line, you need to be sure how the expression is evaluated.

Change:

words[i=(i+1)%words.length]

to:

words[i=(++i)%words.length]

And set i=-1; to start.

Now the (++i) makes sure i is incremented by 1 immediately, before rest of the expression, that's why we need to start at -1. From there it's all good.

It's an alternative to already posted answer if you wanna keep the expression with increment instead breaking the increment to another row.

General difference of ++i and i++ is same across many languages so it's worth looking into it:

SO post with quick explanation

SO post with better explanation but in diff language

DanteTheSmith
  • 2,937
  • 1
  • 16
  • 31