Here's the code, but instead of it completely disappears, is there some way to make it go 0.5 opacity? Help on this would be much appreciated.
$(function () {
var timer;
var fadeInBuffer = false;
$(document).mousemove(function () {
if (!fadeInBuffer) {
if (timer) {
console.log("clearTimer");
clearTimeout(timer);
timer = 0;
}
console.log("fadeIn");
$('.fade-object').fadeIn();
$('html').css({
cursor: ''
});
} else {
fadeInBuffer = false;
}
timer = setTimeout(function () {
console.log("fadeout");
$('.fade-object').fadeOut()
$('html').css({
cursor: 'none'
});
fadeInBuffer = true;
}, 2000)
});
});
You can use fadeTo(). Hope this helps.
$(function () {
var timer;
var fadeInBuffer = false;
$(document).mousemove(function () {
if (!fadeInBuffer) {
if (timer) {
clearTimeout(timer);
timer = 0;
}
$('.fade-object').fadeTo('slow', 1);
$('html').css({
cursor: ''
});
} else {
fadeInBuffer = false;
}
timer = setTimeout(function () {
$('.fade-object').fadeTo('slow', 0.5)
$('html').css({
cursor: 'none'
});
fadeInBuffer = true;
}, 2000)
});
});
.fade-object{
height: 300px;
background: red;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fade-object"></div>
** UPDATED **
Try using setInterval instead of setTimeout, and vary from 10 to 0 to disapear and from 0 to 10 to reapear (according to filenames).
Do this by changing trhough custom png cursors with alfas from 0 to 100 in 10 phases.
Here are some images I prepared: , , , , , , , , , , << last one is 0%
Remember that your cursor (mouse pointer) WON'T change its custom image IF it is NOT moving **, so .. you will need to translate cursor at least 10px programatically while iterating trhough the 10 images.
** UPDATE 2 **
Here you can feel the idea.
//codepen.io/jjyepez/pen/xEQAXZ
PS (forget about translating cursor .. it is not necessary whatsoever)
Related
I have a 'theme toggle' which changes the look/feel of my UI. There is also a custom JS cursor that I don't need on one of the themes. I thought it would be a good idea to kill the script when the relevant class is on html as there's a lot of calculation going on with the pointer position. Rather than just use display: none and leave the script running.
There are 3 modes/themes:
Default (always first / onload)
Dark
Retro - which is the one where the script should be stopped.
I tried to achieve this using the following method. To test, I add the .retro class to html so it's the first theme, it does stop the script from running and clicking the toggle turns the script on again. But it only does it once.
Obviously removing the class onload doesn't work either but I just wanted to do the above to see if anything was happening. Can someone tell me where I'm going wrong. What's the best approach?
Essentially what I'm trying to achieve is: Run this script, unless the class .retro is present, if so stop it. If the class .retro is removed, run the script again.
/* Toggle */
const html = document.querySelector("html");
const button = document.querySelector(".contrast__link");
button.addEventListener("click", (e) => {
e.preventDefault();
if (html.classList.contains("dark-mode")) {
html.classList.remove("dark-mode");
html.classList.add("retro");
let slideIndex = swiper.activeIndex;
swiper.destroy(true, true);
swiper = initSwiper("slide", false, 999999999); // Retro: This should slide, no autoplay or loop
swiper.slideTo(slideIndex, 0);
} else if (html.classList.contains("retro")) {
html.classList.remove("retro");
let slideIndex = swiper.activeIndex;
swiper.destroy(true, true);
swiper = initSwiper("fade", true, 1200); // Default: This should fade, autoplay & loop
swiper.slideTo(slideIndex, 0);
} else {
html.classList.add("dark-mode");
}
});
/* Cursor */
function createHandler(callback) {
return function(event) {
if (!document.documentElement.classList.contains('retro')) {
callback.call(this, event)
}
}
}
window.addEventListener('mousemove', createHandler(function() {
var cursor = document.querySelector(".cursor");
var cursorTrail = document.querySelector(".cursor-trail");
var a = document.querySelectorAll("a");
var timeout;
window.addEventListener(
"mousemove",
function(e) {
var x = e.clientX;
var y = e.clientY;
cursor.style.transform = `translate(${x - 2}px, ${y - 2}px)`;
if (!timeout) {
timeout = setTimeout(function() {
timeout = null;
cursorTrail.style.transform = `translate(${x - 16}px, ${y - 16}px)`;
}, 24);
}
},
false
);
/**
* Add/remove classes on click (anywhere).
*/
document.addEventListener("mousedown", function() {
cursor.classList.add("cursor--click");
});
document.addEventListener("mouseup", function() {
cursor.classList.remove("cursor--click");
});
/**
* Add/remove set classes on hover.
*
* 1. This used to start with `a.forEach((item) => {` but changed to `let` so
* that an additional (non-anchor) item could be targeted. `#hello` is for
* the image on the 404 page.
*/
// a.forEach((item) => {
let links = document.querySelectorAll('a, #hello'); /* [1] */
links.forEach((item) => { /* [1] */
item.addEventListener("mouseover", () => {
cursorTrail.classList.add("cursor-trail--hover");
});
item.addEventListener("mouseleave", () => {
cursorTrail.classList.remove("cursor-trail--hover");
});
});
/**
* Add custom classes on hover if the cursor needs to be manipulated in a
* unique way. If an element has a `data-interaction=""` value set. This will
* be added as a class to the cursor on hover. For example, this is used to
* style the prev/next arrows on the carousel.
*
* This could be set using a specific class but I've just left it targeting all
* `a` elements for now. Which will add a class of `undefined` if no dataset is
* specified.
*/
a.forEach((item) => {
const interaction = item.dataset.interaction;
item.addEventListener("mouseover", () => {
cursor.classList.add(interaction);
});
item.addEventListener("mouseleave", () => {
cursor.classList.remove(interaction);
});
});
}))
.contrast__link {
background: white;
}
.cursor {
background: red;
height: 20px;
width: 20px;
position: fixed;
}
.dark-mode {
background: black;
}
.retro {
background: blue;
}
Toggle Classes
<div class="cursor"><span></span></div>
<div class="cursor-trail"></div>
I would suggest to add and remove "mousemove" listener inside "click" listener, when you toggling the theme. So if user selects "retro", the event listener should be removed, and when it is another theme, the listener should be added.
As #Mykhailo Svyrydovych suggested, to avoid any overhead of the unneeded events call, you would need to have explictly named functions for each event handler, then you could use removeEventListener when you're toggling to the retro theme, removing the handler of each mousemove, mouseenter, mouseleave, mouseup and mousedown events that you don't want to run on that theme. Of course, you would need to re-bind all the events again using the proper addEventListener calls when toggling to the other two themes.
But I think that, sometimes, the easiest approach is good enough. If you measure the performance and then discover that the events keeping to fire isn't a big concern for your case, go for it. You can easily avoid the unwanted effects of the custom cursor, inside each event handler, just by checking a simple boolean:
const html = document.documentElement;
const button = document.querySelector(".contrast__link");
const cursor = document.querySelector(".cursor");
const cursorTrail = document.querySelector(".cursor-trail");
const a = document.querySelectorAll("a");
let timeout;
let customCursor = true;
button.addEventListener("click", (e) => {
e.preventDefault();
if (html.classList.contains("dark-mode")) {
html.classList.remove("dark-mode");
html.classList.add("retro");
customCursor = false;
cursor.style.display = "none";
} else if (html.classList.contains("retro")) {
html.classList.remove("retro");
customCursor = true;
cursor.style.display = "block";
} else {
html.classList.add("dark-mode");
customCursor = true;
cursor.style.display = "block";
}
});
window.addEventListener(
"mousemove",
function(e) {
if (!customCursor) return;
var x = e.clientX;
var y = e.clientY;
cursor.style.display = "block";
cursor.style.transform = `translate(${x - 2}px, ${y - 2}px)`;
if (!timeout) {
timeout = setTimeout(function() {
cursorTrail.style.transform = `translate(${x - 16}px, ${y - 16}px)`;
}, 24);
}
},
false
);
document.addEventListener("mousedown", () => {
if (!customCursor) return;
cursor.classList.add("cursor--click");
});
document.addEventListener("mouseup", () => {
if (!customCursor) return;
cursor.classList.remove("cursor--click");
});
let links = document.querySelectorAll('a, #hello');
links.forEach((item) => {
item.addEventListener("mouseover", () => {
if (!customCursor) return;
cursorTrail.classList.add("cursor-trail--hover");
});
item.addEventListener("mouseleave", () => {
if (!customCursor) return;
cursorTrail.classList.remove("cursor-trail--hover");
});
});
a.forEach((item) => {
const interaction = item.dataset.interaction;
item.addEventListener("mouseover", () => {
if (!customCursor) return;
cursor.classList.add(interaction);
});
item.addEventListener("mouseleave", () => {
if (!customCursor) return;
cursor.classList.remove(interaction);
});
});
.contrast__link {
background: white;
}
.cursor {
background: red;
height: 20px;
width: 20px;
position: fixed;
display: none;
}
.dark-mode {
background: black;
}
.retro {
background: blue;
}
Toggle Classes
<div class="cursor"><span></span></div>
<div class="cursor-trail"></div>
P.S.: I removed the Swiper calls from my code sample because they appeared to be totally unrelated to the question being asked, and were causing console errors.
I have tried with simple CSS code, it's working
.retro .cursor{
display:none
}
but you want to stop the function also, so tried the following that also worked. When the theme is retro on mouse move the cursor changing function is not calling
/* Toggle */
const html = document.querySelector("html");
const cursor = document.querySelector(".cursor");
function addClass() {
if (html.classList.contains("dark-mode")) {
html.classList.remove("dark-mode");
html.classList.add("retro");
cursor.style.display = 'none'
} else if (html.classList.contains("retro")) {
html.classList.remove("retro");
} else {
html.classList.add("dark-mode");
}
}
document.addEventListener('mousemove', function(e) {
if (html.classList.contains("retro")) {
cursor.style.display = 'none'
} else {
cursor.style.display = 'block'
var x = e.clientX;
var y = e.clientY;
cursor.style.transform = `translate(${x - 2}px, ${y - 2}px)`;
}
});
.cursor {
background: red;
height: 20px;
width: 20px;
position: fixed;
}
.dark-mode {
background: black;
}
.retro {
background: blue;
}
<div class="cursor"></div>
<button onclick='addClass()'>Add Class</button>
You can use element insertion and window properties to load/unload code.
Look at code in snippet, there's simple system for theme changing.
When on retro, mouse clicks will be logged in console.
In my snippet, script will be working only on retro theme, but that doesn't changes concept.
const themeList = {
'default': {
enable() {
app.classList.add('default');
},
disable() {
app.classList.remove('default');
},
},
'dark-mode': {
enable() {
app.classList.add('dark-mode');
},
disable() {
app.classList.remove('dark-mode');
},
},
'retro': {
enable() {
app.classList.add('retro');
js = document.createElement("script");
js.id = 'retroThemeScript';
js.innerHTML = `
window.fnToBeRemoved = () => console.log('mouse down');
app.addEventListener("mousedown", window.fnToBeRemoved);
` // you can replace code with next line, so no need to store code in RAM
//js.src = '/scripts/retroScript.js';
js.type = 'text/javascript';
app.appendChild(js);
this.scriptElement = js;
},
disable() {
app.classList.remove('retro');
app.removeEventListener('mousedown', window.fnToBeRemoved);
delete window.fnToBeRemoved;
app.removeChild(this.scriptElement);
},
}
}
const app = document.querySelector('#app');
let currentTheme;
function setTheme(themeName) {
if (currentTheme)
themeList[currentTheme].disable();
themeList[themeName].enable();
currentTheme = themeName;
}
setTheme('default');
#app {
font-size: 24px;
width: 500px;
height: 500px;
background: silver;
}
#app.retro{
background: magenta;
}
#app.dark-mode {
background: gray;
}
<button onclick="setTheme('default')">Default</button>
<button onclick="setTheme('dark-mode')">Dark</button>
<button onclick="setTheme('retro')">Retro</button>
<div id="app">
Wanna cake?
</div>
I'm trying to create a very simple 2D game where you run forward automatically and then jump at keypress to avoid obstacles along the course.
I made this so far. The only issue is that jumping "stops" the forward-motion. And if you for example hold the up button it stops the entire game and you keep flying upwards like a bird...
Can anyone give me some advice on how to fix it? I would also LOVE it if someone could guide me in how to place 1-2 random obstacles along the course and restart the game, also show total position left traveled if those obstacles are hit by the user.
My plan is to speed up the game every time you finish a course!
Thanks a lot in advance :)
<div style='' id='map'></div>
$(function(){
var unjump = function(){
$('#player').stop().animate({
bottom: '33'
});
}
var jump = function(){
$('#player').stop().animate({
bottom: '+=100'
});
setTimeout(unjump, 1000);
}
$(document).keydown(function(e) {
switch(e.which) {
case 38: // up
jump();
break;
}
});
var player = '<div id="player"></div>';
$("#map").append(player);
function run(){
var position = $('#player').position();
var width = $('#map').width();
if (position.left > width){
$("#player").css( "left", 0 );
}
$('#player').stop().animate({
left: '+=200'
});
}
run = setInterval(run, 100);
});
DEMO
the main error was in css positioning of player
css code
#player{
width:10px;
height:10px;
border:solid;
position:absolute;
bottom:0px;
}
#map{
position:relative;
}
html code
<div style='border:solid ;height:100px' id='map'></div>
js code
var interval = null;
var interval2 = null;
$(function () {
var player = '<div id="player"></div>';
$("#map").append(player);
var unjump = function () {
$('#player').stop().animate({
bottom: '0'
});
};
var jump = function () {
$('#player').stop().animate({
bottom: '+=100'
}, 500);
interval2 = setTimeout(unjump, 500);
};
$(document).keydown(function (e) {
switch (e.which) {
case 38: // up
jump();
break;
}
});
function run() {
var width = $('#map').width();
if ($('#player').position().left > width) {
$("#player").css("left", 0);
}
$('#player').stop().animate({
left: '+=10'
});
}
interval = setInterval(run, 500);
});
Try this:
https://fiddle.jshell.net/u8deLxkz/2/
Main issue was to perform run animation only if no other animation is running.
Except for that, I tidied up the code a little.
$(function(){
//No need for two separate functions, left is handled here as well
function jump(){
$('#player').animate({
bottom: '+=30',
left: '+=10'
},100).animate({
bottom: '-=30',
left: '+=10'
},100);
}
//I think keyup gives better results
$(document).keyup(function(e) {
switch(e.which) {
case 38: //up
jump();
break;
}
});
var player = '<div id="player" style="width: 50px; height: 50px; background-color: blue; position:absolute; bottom:500px;"></div>';
$("#map").append(player);
function run(){
var position = $('#player').position();
var width = $('#map').width();
$('#player').position()
console.log('pos ' + position.left + "\nwidth: " + width);
if (position.left > width){
$("#player").finish();
$("#player").css( "left", 0 );
}
//Continue with horizontal animation only if jumping is not in progress
if(!$('#player').is(':animated') ){
$('#player').animate({
left: '+=10'
},100);
}
}
var go = setInterval(run, 100);
});
I'm creating an animation of a ring rotating.
On hover the right rotates 180 degrees, pauses and rotates back to the starting position. If the user removes the cursor off the ring while its animating it needs to reverse from the frame its currently on.
I haven't had much extensive experience with animation in my career as a front end developer so any advice on tech to use would be appreciated.
Currently I'm using CSS Animation with a sprite, as below but it lacks the ability to reverse from the frame it was on when the user leaves the ring.
Here is my working example, It's inspired by http://renren.com/
Example using CSS
$('body').on('mouseenter', '.item', function() {
$(this).removeClass('unactive').addClass('active');
});
$('body').on('mouseleave', '.item', function() {
$(this).removeClass('active').addClass('unactive');
});
.content {
width: 150px;
height: 150px;
background-color: #EBEBEB;
}
.content.ring {
background: url(http://a.xnimg.cn/nx/apps/login/cssimg/qrcode1-t.jpg) 0 0 no-repeat
}
.active .content {
background-position: 0 -1800px;
-moz-animation: movedown 2000ms steps(12) forwards;
-webkit-animation: movedown 2000ms steps(12) forwards
}
.unactive .content {
-moz-animation: moveup 2000ms steps(7) forwards;
-webkit-animation: moveup 2000ms steps(7) forwards
}
#-moz-keyframes movedown {
0% {
background-position: 0 0
}
100% {
background-position: 0 -1800px
}
}
#-moz-keyframes moveup {
0% {
background-position: 0 -1800px
}
100% {
background-position: 0 -2850px
}
}
#-webkit-keyframes movedown {
0% {
background-position: 0 0
}
100% {
background-position: 0 -1800px
}
}
#-webkit-keyframes moveup {
0% {
background-position: 0 -1800px
}
100% {
background-position: 0 -2850px
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTML
<div class="item active">
<div class="content ring">
</div>
</div>
I've also found plugins like:
motio
So my question is, is CSS able to have this much control or would a CANVAS or other jQuery plugin be better suited?
EDIT
I'm still having difficulties figuring this one out although I started writing a script to help control the animation.
I'm trying to control the background position to gain control of the sprite rotating.
Example using Javascript
;(function($) {
var Ring = function (options) {
// context
var self = this;
// defaults
var currFrame = 1, totalFrames, width, height, timeout;
// default frame array
var framesObj = {};
// option defaults
self.class = "";
self.spriteHeight = "";
//properties based on options
if (typeof options != 'undefined' && options != undefined && options != null)
{
self.class = options.class;
self.spriteHeight = options.spriteHeight;
self.speed = options.speed;
}
// fire off everything you need
self.init = function ()
{
self.buildArr();
}
// check for the container dimentions
self.frameDimentions = function ()
{
// double check we have a class to select the container with
var container = self.class ? true : false;
// I know I could just write self.class in the if..
if ( container )
{
var container = $("." + self.class + "");
var containerHeight = container.outerHeight();
var containerWidth = container.outerWidth();
return [containerHeight,containerWidth];
}
console.log("Please provide a class");
}
// calculate frames e.g. 3000 into 150 per frame is 20..
self.calcFrames = function()
{
var totalFrames = parseInt(self.spriteHeight) / self.frameDimentions()[0];
return totalFrames;
}
self.buildArr = function()
{
// these values need to be pushed in to the arr
for (var i = 0; i < self.calcFrames(); i++) {
framesObj[(i+1)] = self.frameDimentions()[0]*i;
}
}
self.startForwardAnimation = function(){
// to stop manic clicking../hover..
if( currFrame <= 1 )
{
timeout = setInterval( updateFrameForward, self.speed);
}
}
self.startBackwardAnimation = function(){
// to stop manic clicking../hover..
console.log("start backward animation");
if( currFrame != 1 )
{
backTimeout = setInterval( updateFrameBackward, self.speed);
}
}
self.stopAnimation = function(){
//currFrame = 1;
clearTimeout(timeout);
}
self.reset = function(){
clearTimeout(timeout);
clearTimeout(backTimeout);
currFrame = 1;
}
self.info = function(){
$('.info').html(currFrame);
}
// if currFrame less than total frames
// add one to it
// update the current frame variable
// stop and clear timer when reach the end
function updateFrameForward(){
//check if we are in available frames..
if ( currFrame == self.calcFrames() )
{
self.stopAnimation();
self.reset();
}
$("." + self.class + "").css({
'background-position-y': "-" + framesObj[currFrame] + "px"
});
self.info();
currFrame = currFrame + 1;
}
function updateFrameBackward(){
if( currFrame <= 1 )
{
self.stopAnimation();
self.reset();
}
$("." + self.class + "").css({
'background-position-y': framesObj[currFrame] + "px"
});
self.info();
console.log(currFrame);
currFrame = currFrame - 1;
}
}
var ringAniamtion = new Ring({
class: "animate",
spriteHeight: "3000",
speed: "20"
});
$('body').on('mouseenter', '.animate', function(event){
event.preventDefault();
console.log("mouse enter");
ringAniamtion.buildArr();
ringAniamtion.startForwardAnimation();
});
$('body').on('mouseleave', '.animate', function(event){
event.preventDefault();
console.log("mouse leave");
ringAniamtion.stopAnimation();
ringAniamtion.startBackwardAnimation();
});
$('body').on('click', '.stop', function(event){
event.preventDefault();
ringAniamtion.reset();
});
})( jQuery );
// timeout = setTimeout('timeout_trigger()', 3000);
// clearTimeout(timeout);
.content
{
width: 150px;
height: 150px;
background: url(http://a.xnimg.cn/nx/apps/login/cssimg/qrcode1-t.jpg) 0 0 no-repeat;
cursor: pointer;
}
<div class="content animate">
</div>
<div class="info">
</div>
stop
I figured out how to do it in the second code snippet..
;(function($) {
var Ring = function (options) {
// context
var self = this;
// defaults
var currFrame = 1, totalFrames, width, height, timeout;
// default frame array
var framesObj = {};
// option defaults
self.class = "";
self.spriteHeight = "";
//properties based on options
if (typeof options != 'undefined' && options != undefined && options != null)
{
self.class = options.class;
self.spriteHeight = options.spriteHeight;
self.speed = options.speed;
}
// fire off everything you need
self.init = function ()
{
self.buildArr();
}
// check for the container dimentions
self.frameDimentions = function ()
{
// double check we have a class to select the container with
var container = self.class ? true : false;
// I know I could just write self.class in the if..
if ( container )
{
var container = $("." + self.class + "");
var containerHeight = container.outerHeight();
var containerWidth = container.outerWidth();
return [containerHeight,containerWidth];
}
console.log("Please provide a class");
}
// calculate frames e.g. 3000 into 150 per frame is 20..
self.calcFrames = function()
{
var totalFrames = parseInt(self.spriteHeight) / self.frameDimentions()[0];
return totalFrames;
}
self.buildArr = function()
{
// these values need to be pushed in to the arr
for (var i = 0; i < self.calcFrames(); i++) {
framesObj[(i+1)] = self.frameDimentions()[0]*i;
}
}
self.startForwardAnimation = function(){
// to stop manic clicking../hover..
if( currFrame <= 1 )
{
timeout = setInterval( updateFrameForward, self.speed);
}
}
self.startBackwardAnimation = function(){
// to stop manic clicking../hover..
console.log("start backward animation");
if( currFrame != 1 )
{
backTimeout = setInterval( updateFrameBackward, self.speed);
}
}
self.stopAnimation = function(){
//currFrame = 1;
clearTimeout(timeout);
}
self.reset = function(){
clearTimeout(timeout);
clearTimeout(backTimeout);
currFrame = 1;
}
self.info = function(){
$('.info').html(currFrame);
}
// if currFrame less than total frames
// add one to it
// update the current frame variable
// stop and clear timer when reach the end
function updateFrameForward(){
//check if we are in available frames..
if ( currFrame == self.calcFrames() )
{
self.stopAnimation();
self.reset();
}
$("." + self.class + "").css({
'background-position-y': "-" + framesObj[currFrame] + "px"
});
self.info();
currFrame = currFrame + 1;
}
function updateFrameBackward(){
if( currFrame <= 1 )
{
self.stopAnimation();
self.reset();
}
$("." + self.class + "").css({
'background-position-y': framesObj[currFrame] + "px"
});
self.info();
console.log(currFrame);
currFrame = currFrame - 1;
}
}
var ringAniamtion = new Ring({
class: "animate",
spriteHeight: "3000",
speed: "20"
});
$('body').on('mouseenter', '.animate', function(event){
event.preventDefault();
console.log("mouse enter");
ringAniamtion.buildArr();
ringAniamtion.startForwardAnimation();
});
$('body').on('mouseleave', '.animate', function(event){
event.preventDefault();
console.log("mouse leave");
ringAniamtion.stopAnimation();
ringAniamtion.startBackwardAnimation();
});
$('body').on('click', '.stop', function(event){
event.preventDefault();
ringAniamtion.reset();
});
})( jQuery );
How can I change this script from jQuery to JavaScript? I have little experience with JavaScript and I don't know how to change it myself.
Script:
var rotate = function() {$("#Top")
.delay(1000).queue(function() {
$(this).css({
"background-color": "red"
});
$(this).dequeue();
})
.delay(3000).queue(function() {
$(this).css({
"background-color": "green"
});
$(this).dequeue();
})
.delay(500).queue(function(next) {
$(this).css({
"background-color": "blue"
});
$(this).dequeue();
next();
})
.queue(rotate);
};
rotate();
Html
<div id="Top"></div>
Original: http://jsfiddle.net/h4KL7/1/
John Resig is the guy who wrote jQuery and here is a blurb about How JavaScript Timers Work.
I know it is not perfect and could use setInterval() and clearInterval() to be more efficient, but this is a start DEMO
var rotate = function () {
var el = document.getElementById('Top');
setTimeout(function () {
el.style.backgroundColor = 'red';
setTimeout(function () {
el.style.backgroundColor = 'green';
setTimeout(function () {
el.style.backgroundColor = 'blue';
rotate();
}, 500);
}, 3000);
}, 1000);
}
Update: Added an array to reference timeout IDs to ensure that duplicates are not created in case time gets out of sync.
var rotate = function () {
var el = document.getElementById('Top');
var timers = new Array(3);
function red(el) {
el.style.backgroundColor = 'red';
timers[0] = setTimeout(function () { green(el); }, 1000);
clearTimeout(timers[2]);
}
function green(el) {
el.style.backgroundColor = 'green';
timers[1] = setTimeout(function () { blue(el); }, 3000);
clearTimeout(timers[0]);
}
function blue(el) {
el.style.backgroundColor = 'blue';
timers[2] = setTimeout(function () { red(el); }, 500);
clearTimeout(timers[1]);
}
red(el);
};
rotate();
The title of your post should be: "How can I change this from jQuery to CSS" ;-)
#-webkit-keyframes rainbow {
0% { background: #FFABAB; }
20% { background: #FFDAAB; }
40% { background: #DDFFAB; }
60% { background: #ABE4FF; }
80% { background: #D9ABFF; }
100% { background: #FFABAB; }
}
.top {
min-height: 200px;
-webkit-animation: rainbow 10s infinite steps(1);
}
If you want to have smooth transition between your background color just omit the steps(1) in the animation shorthand property.
Check this out!
I want text to bounce of the left and right sides of a div tag (#header). It works fine when it bounces of the right, then goes back and hits the left. The problem is that after it hits the left and starts to go right again it never hits the right side. It just keeps going and the window scrollbar appears. It appears as soon as it hits the left side. It seems that the div tag.
var finishedGoingRight = false;
setInterval(function() {
slideText();
}, 10);
function slideText(){
if(!finishedGoingRight){
$('#header h1').css("right","-=1");
}else{
$('#header h1').css("left","-=1");
}
if($('#header h1').css("right") == "20px"){
finishedGoingRight = true;
}
if($('#header h1').css("left") == "485px"){
finishedGoingRight = false;
}
}
Hope I explained it clearly :)
Debugging your code revealed that $('#header h1').css("right") always equals "auto", unless you've set it explicitly somewhere.
This works:
http://jsfiddle.net/7z3a3/1/
var finishedGoingRight = false;
setInterval(function() { slideText(); }, 10);
function slideText() {
if (!finishedGoingRight) {
$('#header h1').css("left", "+=1");
} else {
$('#header h1').css("left", "-=1");
}
if ($('#header h1').position().left >= $('#header').width()-$('#header h1').width()) {
finishedGoingRight = true;
} else if ($('#header h1').position().left <= 0) {
finishedGoingRight = false;
}
}
Here's my solution using animate:
JS:
var inner = $('#inner'), widthInner = inner.width(), outer = $('#outer'), widthOuter = outer.width();
function animateRight() {
inner.animate({ left: widthOuter - widthInner }, 1000, function() {
animateLeft();
});
}
function animateLeft() {
inner.animate({ left: 0 }, 1000, function() {
animateRight();
});
}
animateRight();
HTML
<div id="outer"><h2 id="inner">Inner</h2></div>
CSS
div, h2 { border: 1px solid black; }
#outer { width: 300px; height: 200px; }
#inner { margin-top: 75px; width: 50px; position: relative; }
http://jsfiddle.net/rHEQA/2/