Ihidan Ihidan - 3 months ago 10
Javascript Question

Displaying Message with fade-in/fade-out on JS

Given the following tags:

<h1 id="header_one"><strong>Any Title</strong> any message</h1>

<p id="paragraph_one">Any cool text.<br></p>


And the following JS arrays:

var array_h = ["<strong>Any Title1</strong> any message","<strong>Any Title2</strong> any message"];
var array_p = ["Any cool text1 <br>","Any cool text2 <br>"];


How may I change the message of h1 and p according to each element of the array using a fade-in/fade-out effect? I wish the effect would repeat forever starting it again when it reached the last message of the array.

Answer

You can use some jquery:

    <h1 id="header_one"><strong>Any Title</strong> any message</h1>

    <p id="paragraph_one">Any cool text.<br></p>

var array_h  = ["<strong>Any Title1</strong> any message","<strong>Any Title2</strong> any message"];
var array_p  = ["Any cool text1 <br>","Any cool text2 <br>"];
var curIndex = 0;
var changeheader = function(){
  var header = $('#header_one');
  header.fadeOut(function(){
    header.html(array_h[curIndex]);
    header.fadeIn();
    curIndex = (curIndex + 1) % array_h.length;
  setTimeout(changeheader,1000);
  });

}

var curIndex2 = 0;
var changep = function(){

  var p = $('#paragraph_one');
  p.fadeOut(function(){
    p.html(array_p[curIndex2]);
    p.fadeIn();
    curIndex2 = (curIndex2 + 1) % array_p.length;
  setTimeout(changep,1000);
  });

}
setTimeout(changeheader,1000);
setTimeout(changep,1000);

working example: http://codepen.io/nilestanner/pen/akAVkr

This allows for any number of elements in the array

Comments