Introduction
In this article I'll show how to use jsTimers-rAF, a library that makes use
of RequestAnimationFrame
simply as the use of setTimeout
or
setInterval
function.
In github there're some examples of use, but now I'll show how to use the library to change the background on the page, as a div,
or what else you can imagine to do with requestAnimationFrame
.
CSS
To change the page background, I decided to use CSS classes: first set a class to HTML tag.
<!doctype html>
<html class="htmlBg1"> ....</html>
and then I declared these classes into style:
.htmlBg1 {
background: linear-gradient(135deg, #004003 0%, #78F170 100%, #23AC28 100%) repeat scroll 0 0 transparent;
background: -webkit-linear-gradient(135deg, #004003 0%, #78F170 100%, #23AC28 100%) repeat scroll 0 0 transparent;
background: -ms-linear-gradient(135deg, #004003 0%, #78F170 100%, #23AC28 100%) repeat scroll 0 0 transparent;
}
.htmlBg2 {
background: linear-gradient(130deg, #004003 2%, #78F170 95%, #23AC28 97%) repeat scroll 0 0 transparent;
background: -webkit-linear-gradient(130deg, #004003 2%, #78F170 95%, #23AC28 97%) repeat scroll 0 0 transparent;
background: -ms-linear-gradient(130deg, #004003 2%, #78F170 95%, #23AC28 97%) repeat scroll 0 0 transparent;
}
.htmlBg3 {
background: linear-gradient(125deg, #004003 5%, #78F170 90%, #23AC28 95%) repeat scroll 0 0 transparent;
background: -webkit-linear-gradient(125deg, #004003 5%, #78F170 90%, #23AC28 95%) repeat scroll 0 0 transparent;
background: -ms-linear-gradient(125deg, #004003 5%, #78F170 90%, #23AC28 95%) repeat scroll 0 0 transparent;
}
Now it's JavaScript time: import the library into HTML code and before "</body>" insert a new script tag with this code:
<body>
.....
<script>
myIntervalId = null;
stopBkChange = 1;
classCounter = 3;
function changeBk() {
stopBkChange--;
if(stopBkChange < 0) stopBkChange=0;
if(myIntervalId==null && stopBkChange == 0) {
myIntervalId = myInterval(function() {
if(myAdd == classCounter) bgIncr = false;
else if(myAdd == 1) bgIncr = true;
if(bgIncr) myAdd++; else myAdd--;
myTag.setAttribute("class", "htmlBg"+myAdd);
}, 750);
}
}
function stopChangeBk(){
if(stopBkChange == 0) {
myClearInterval(myIntervalId);
myIntervalId=null;
}
stopBkChange++;
}
if(trAfHack.rAFSupported() == true) {
myInterval = trAfHack.setInterval;
myClearInterval = trAfHack.clearInterval;
} else {
myInterval = window.setInterval.bind(window);
myClearInterval = window.clearInterval.bind(window);
}
var myTag = document.querySelector("html");
var myAdd = 1;
var bgIncr = true;
changeBk();
document.addEventListener("focus", changeBk);
document.addEventListener("blur", stopChangeBk);
</script>
</body>
</html>
Points of Interest
You can reuse this code as you like, to change the behavior you just:
- edit/add CSS classes
- change
classCounter
- instead of HTML, select the tag of you interest
var myTag = document.querySelector("html");