I am so used to working with jQuery that I can't seem to figure out how I can do this in plain Javascript. I don't want to use jQuery because this is the only snippet that I use on the site and the library is too large for only that purpose.
This is the jQuery script (working): http://jsfiddle.net/1jt6dhzu/2/
$(document).ready(function () {
var whatAmI = ["Fruit", "Not a vegetable", "A phone", "Yummie in tummy"];
var j, i = 4,
n = whatAmI.length;
function changeSubTitle() {
setTimeout(function () {
j = Math.floor(Math.random() * n - 1);
if (j >= i) j += 1;
$(".page-header > h2").animate({
"opacity": 0
}, 700, function () {
$(this).children("span").text(whatAmI[j]);
$(this).animate({
"opacity": 1
}, 700, changeSubTitle);
});
}, 1000);
i = j;
}
changeSubTitle();
});
And I want to swap it for vanilla JS. A large part of the loop can stay, however, the timeout and callbacks have to be replaced. I figured because I don't need IE9 support I could do this with css3 transitions and add classes. This is what I have so far:
h2 {
opacity: 1;
transition: opacity 700ms;
}
h2.fade-out {
opacity: 0;
}
document.addEventListener("DOMContentLoaded", function () {
var whatAmI = ["Fruit", "Not a vegetable", "A phone", "Yummie in tummy"];
var j, i = 4,
n = whatAmI.length,
heading = document.querySelector(".page-header > h2");
function changeSubTitle() {
setTimeout(function () {
j = Math.floor(Math.random() * n - 1);
if (j >= i) j += 1;
heading.classList.add("fade-out");
setTimeout(function () {
heading.children("span")[0].innerHTML = whatAmI[j];
heading.classList.remove("fade-out");
setTimeout(changeSubTitle, 700);
}, 700);
}, 1000);
i = j;
}
changeSubTitle();
});
Unfortunately this doesn't work. It would probably be better to swap out the timeOuts (except the most outer one) for events on transitionend. But I'm not sure how to implement this crossbrowser (IE 10 and higher, and other major browsers).