This is quite an unusual request, but..
Is there anyway to make some text alternate between 2 colors every second?
So it appears as though it's flashing between say... red and grey? I don't mean background color, I mean the actual font color. I'm assuming it would need javascript or something.
Is there any simple way to do that?
(disregarding the fact it could look ugly)
UPDATE
Id like to call to this function several times on my page, each one passing along a different color to alternate with GREY
.
As per your request:
function flashtext(ele,col) {
var tmpColCheck = document.getElementById( ele ).style.color;
if (tmpColCheck === 'silver') {
document.getElementById( ele ).style.color = col;
} else {
document.getElementById( ele ).style.color = 'silver';
}
}
setInterval(function() {
flashtext('flashingtext','red');
flashtext('flashingtext2','blue');
flashtext('flashingtext3','green');
}, 500 ); //set an interval timer up to repeat the function
JSFiddle here: http://jsfiddle.net/neuroflux/rXVUh/14/
Here's an easy way to do it with plain JavaScript:
function flash() {
var text = document.getElementById('foo');
text.style.color = (text.style.color=='red') ? 'green':'red';
}
var clr = setInterval(flash, 1000);
This will alternate the color of the text between red and green every second. jsFiddle example.
Here's another example where you can set the colors of different elements:
function flash(el, c1, c2) {
var text = document.getElementById(el);
text.style.color = (text.style.color == c2) ? c1 : c2;
}
var clr1 = setInterval(function() { flash('foo1', 'gray', 'red') }, 1000);
var clr2 = setInterval(function() { flash('foo2', 'gray', 'blue') }, 1000);
var clr3 = setInterval(function() { flash('foo3', 'gray', 'green') }, 1000);
and the jsFiddle to go with it. You pass the ID of the element you want to flash and the two colors to alternate between.
With JavaScript it is very simple:
function alternateColor(color, textId, myInterval) {
if(!myInterval){
myInterval = 1000;
}
var colors = ['grey', color];
var currentColor = 1;
document.getElementById(textId).style.color = colors[0];
setInterval(function() {
document.getElementById(textId).style.color = colors[currentColor];
if (currentColor < colors.length-1) {
++currentColor;
} else {
currentColor = 0;
}
}, myInterval);
}
alternateColor('red','myText');
Call the function with the first argument being a color, the second being your text's ID, and third being the interval time (optional). Jsfiddle example
Here's some simple easy to understand code.
var count_x = 1,
max_x = 5; // Change this for number of on-off flashes
var flash_color_notify = setInterval(function () {
/* Change the color depending if it's even(= gray) or odd(=red) */
if (count_x % 2 === 0) { // even
$('#element').css('color', 'gray');
} else { // odd
$('#element').css('color', 'red');
}
/* Clear the interval when completed blinking */
if (count_x === max_x * 2) {
clearInterval(flash_color_notify);
} else { count_x += 1; }
}, 500);
Related
I'm making a flipping counter which is supposed to change color when reaching the target number (1000 in the example). But the thing is the different parts of the counter doesn't change color at the same time, we can clearly see a delay between the tiles that make up the counter...
I'm using a simple jQuery addClass to trigger the color change:
$("#rhcounter .count").addClass("red");
Any ideas what could be causing that ?
Here is the fiddle: http://jsfiddle.net/ka6ke28m/6/
Thanks for your help !
First issue:
There was a huge amount of wasted processing going on. jQuery selectors have an overhead so reduce them to a minimum and complex selectors more-so. I have reduced that considerably.
Second issue:
There is a nasty visual glitch on some browsers that looked like this:
Which you can eliminate by using background-color: instead of background: (which tries to completely re-render the area instead of just fill the background colour).
Third issue:
The color blue left behind was down to slow repainting of the screen. The above two fixes had a huge impact and I also tried adding specific CSS animations that worked only with the red class. This can probably be improved now you know the causes of the slow painting (e.g. have blue and red CSS animation?):
http://jsfiddle.net/TrueBlueAussie/ka6ke28m/10/
$(function () {
var total = 1000,
current = 950,
timeout = 150,
inc = 7,
prevTiles = ["0", "0", "0", "0"],
interval = setInterval(function () {
increase()
}, timeout),
increase = function () {
current += inc;
if (current >= total) {
clearInterval(interval);
current = total;
}
if (current === total) {
$("#rhcounter .count").addClass("red");
}
// instant timer to delay css
setTimeout(function () {
var tiles = [false, false, false, false],
currStr = (current + "").split("").reverse().join("");
for (var i = 0; i < currStr.length; i++) {
if (currStr[i] !== prevTiles[i]) {
tiles[i] = true;
prevTiles[i] = currStr[i];
}
}
tiles.forEach(function (tile, index) {
if (!tile) {
return;
}
// Get the current tile
var $tile = $("#rhcounter div.tile" + index);
$tile.children('span.curr').each(function () {
$(this).text($tile.text());
});
$tile.removeClass("flip");
setTimeout(function () {
$tile.addClass("flip");
}, 5);
var top = $tile.find("span.count.next.top"),
bottom = $tile.find("span.count.next.bottom"),
delay = (index === 0 ? timeout : 250);
setTimeout(function () {
top.text(prevTiles[index]);
}, delay / 2);
setTimeout(function () {
bottom.text(prevTiles[index]);
}, delay / 2);
});
}, 1);
};
});
that was happening because you were changing color before changing text. i just shifted if condition and i think that is what you wanted DEMO
$(window).load(function() {
var total = 1000, current = 950, timeout = 150, inc = 7,
prevTiles = ["0","0","0","0"],
interval = setInterval(function(){increase()}, timeout),
increase = function () {
current += inc;
if (current >= total) {
clearInterval(interval);
current = total;
}
var tiles = [false, false, false, false],
currStr = (current+"").split("").reverse().join("");
for (var i = 0; i < currStr.length; i++) {
if (currStr[i] !== prevTiles[i]) {
tiles[i] = true;
prevTiles[i] = currStr[i];
}
}
tiles.forEach(function (tile, index) {
if (!tile) { return; }
$("#rhcounter > div[class~='tile"+index+"'] > span[class~='curr']").each(function() {
$(this).text($("#rhcounter > div[class~='tile"+index+"'] > span.count.next.top").text());
});
$("#rhcounter > div[class~='tile"+index+"']").removeClass("flip");
setTimeout(function(){$("#rhcounter > div[class~='tile"+index+"']").addClass("flip");}, 5);
var top = $("#rhcounter > div[class~='tile"+index+"'] > span.count.next.top"),
bottom = $("#rhcounter > div[class~='tile"+index+"'] > span.count.next.bottom"),
delay = (index === 0 ? timeout : 250);
setTimeout(function(){ top.text(prevTiles[index]); }, delay/2);
setTimeout(function(){ bottom.text(prevTiles[index]); }, delay/2);
});
if (current === total) {
$("#rhcounter .count").addClass("red");
}};
});
http://csdev.cegep-heritage.qc.ca/students/cguigue/primordialCasino/game.html
supposed to click on the spin button and it should start the wheel spinning as well as changed the text on the screen in my displayArea, though when i click spin nothing happens,
getting undefined type error on the following code and not sure as to why
$('#wheel').rotate({
angle: 0,
animateTo: 2520,
duration: 4000
});
it says it isn't a function... :S
also...
if(currentGame.place == 0 && cellText == 0)
{
currentGame.setBet(betAmount * 40);
}
function rouletteGame(num, even, col)
{
this.place = num;
this.isEven = even;
this.colour = col;
this.win = 0;
this.hasBet = false;
this.setBet = function(bet)
{
this.win += bet;
this.hasBet = true;
}
says currentGame.place is undefined
but im initializing it in a for loop and its calling my above function...
for (var i = 1; i < rouletteWheel.length; ++i)
{
place = i;
if(i % 2 == 1)
{
isEven = false;
}
else
{
isEven = true;
}
if( i = red[count])
{
colour = "red";
++count;
}
else
{
colour = "black";
}
rouletteWheel[i] = new rouletteGame(place, isEven, colour);
}// for ()
.rotate() is not a built-in JQuery plugin. You will need to download or link the plugin in order for it to work. Add the following in your element of the HTML:
<script type="text/javascript" src="http://jqueryrotate.googlecode.com/svn/trunk/jQueryRotate.js"></script>
and see if that helps. with the first part of your problem.
As for the second part, I'm not sure if Javascript works this way too (I think it does), but you should create the new roulette game outside of the loop, and only change the values inside. Otherwise you are only creating a new roulette game for use within the scope of the for loop, not outside.
May want to check the documentation for this, as I'm not 100% positive about it. I just know it's how most other languages work.
I a have a list of colors in an array and I would like to make a function that goes through the array and takes the color that is associated with the index of the array to change the background of the div every second. The color of the div should depend on where the index of the array is.
$(document).ready(function(){
var array = ["red", "blue", "yellow"];
var counter = 0;
var nextColor;
function bgchange() {
$(".box").css("backgroundColor", "");
counter = (counter + 1) % array.length;
nextColor = array[counter];
$(".box").css("backgroundColor","'" + nextColor +"'");
}
setInterval(bgchange, 1000)
});
I want to accomplish this task by using the code that is similar to the one above but that actually works.
Thank you for your help in advance.
jsFiddle Demo
Switch backgroundColor to background-color:
function bgchange() {
// $(".box").css("background-color", ""); // Unnecessary command
counter = (counter + 1) % array.length;
nextColor = array[counter];
$(".box").css("background-color", nextColor); // Also no need to wrap
// variables with quotes
}
http://jsfiddle.net/hCKA8/.
<div id="box">...</div>
$(document).ready(function() {
setInterval(function() {
$('#box').animate( { backgroundColor: 'red' }, 1000)
.animate( { backgroundColor: 'green' }, 1000);
}, 1000);
});
I am in the process of applying validation on a web form -one of the things I would like to do is add a pulsing border to the div which contains the erroneous input.
This solution: border highlighting loop with jquery and http://jsfiddle.net/Ue4wy/4/ pretty much hits the mark.
But I want to be able to fade the yellow border to black on the click handler & reset the loop (this example pauses the loop), so the next time the user hits submit it starts again.
Reseting the colour to black works using the code below (though I am sure there is a more elegant solution), but how do I reset the loop?
$('#weight').animate({
borderBottomColor: '#000',
borderLeftColor: '#000',
borderRightColor: '#000',
borderTopColor : '#000'
}, 'fast' );
Any ideas appreciated!
I've updated the update() function to accept an argument, i, which is then called in the click handler, along with window.clearTimeout():
var addClickHandler = function() {
$("div").click(function() {
window.clearTimeout(timer);
update(0);
});
};
This does require that the other calls to update() also need to pass the i:
var update = function(i) {
$("div").css("border-color", 'rgb(' + i + ',' + i + ',' + 0 + ')');
};
JS Fiddle demo.
Edited to amend the click-handler to offer a toggle (stop/start) for the animation:
var addClickHandler = function() {
$("div").toggle(function() {
window.clearTimeout(timer);
update(0);
}, function() {
anim.go();
});
};
JS Fiddle demo.
Edited for a slightly more context-aware click-handler, this version checks for the existence of the timer variable and, if it isn't found, starts the animation. If it is found then it clears the timeout, sets the timer to false and calls update(0) to reset the borders to black:
var addClickHandler = function() {
$("div").click(function() {
console.log(timer);
if (!timer){
timer = window.setTimeout(anim.go, 30);
}
else {
window.clearTimeout(timer);
timer = false;
update(0);
}
});
JS Fiddle demo.
References:
toggle().
window.clearTimeout().
Here's a jQuery UI effect to pulsate the border:
$.effects.borderPulsate = function(o) {
return this.queue(function() {
var elem = $(this),
mode = $.effects.setMode(elem, o.options.mode || 'show'),
times = (o.options.times || 5),
duration = o.duration ? o.duration : $.fx.speeds._default,
isVisible = elem.is(':visible'),
color = (o.options.color || 'rgb(255,255,0)'),
startColor = (o.options.startColor || elem.css('border-color') || 'transparent');
if (!isVisible) {
elem.show();
}
if ((mode == 'hide' && isVisible) || (mode == 'show' && !isVisible)) {
times--;
}
for (var i = 0; i < times; i++) {
elem.animate({ 'border-color': color }, duration, o.options.easing, function() {
elem.css( 'border-color', startColor );
});
}
elem.animate({ 'border-color': color }, duration, o.options.easing, function() {
(o.callback && o.callback.apply(this, arguments));
});
elem
.queue('fx', function() { elem.dequeue(); })
.dequeue();
});
};
http://jsfiddle.net/cdeutsch/TjkNd/
You can change colors on all borders at the same time with borderColor, but you don't need to animate that. You could add a reset method to your object to take care of the whole thing:
var reset = function() {
i = 0;
step = 10;
up = true;
if(timer) window.clearTimeout(timer);
timer = null;
$('#weight').css('borderColor', '#000');
}
Then on your click handler, you call anim.reset() after anim.stop().
I'm looking to start and stop a loop with a set delay with a jQuery hover event. I've been trying to do it with "mouseover" and "mouseout" with no luck.
Example (odd psudocode):
Mouseover
Loop
Change text colour
Wait 100ms
Mouseout
Stop loop
I'm sure this is super easy, I just don't quite know how to structure it with JavaScript.
Thanks in advance.
This might work:
$(function(){
$('#test').hover(function(){
var self = $(this),
rnd = null,
col = null;
this.iid = setInterval(function(){
col = ['#'];
rnd = ~~(Math.random()*255);
col.push(rnd.toString(16).length < 2 ? '0' + rnd.toString(16) : rnd.toString(16));
col.push(rnd.toString(16).length < 2 ? '0' + rnd.toString(16) : rnd.toString(16));
col.push(rnd.toString(16).length < 2 ? '0' + rnd.toString(16) : rnd.toString(16));
self.css({backgroundColor: col.join('')});
}, 100);
}, function(){
if(this.iid){
clearInterval(this.iid);
delete this.iid;
}
});
});
See this in action: http://www.jsfiddle.net/YjC6y/19/
function rgb() {
var color = 'rgb(';
for (var i = 0; i < 3; i++) {
color += Math.floor(Math.random() * 255) + ',';
}
return color.replace(/\,$/, ')')
}
var loop = null;
$(function () {
$('#someid').hover(function () {
var $this = $(this);
loop = setInterval(function () {
$this.css({backgroundColor: rgb() });
}, 100);
}, function () {
clearInterval(loop);
});
});
try an example : http://jsbin.com/uraxe4
$("#yourElem").hover(
function () { /* mousenter */
$this = $(this);
// take note that the mouse is currently hovering
$this.data("isHovering", true);
// create an interval and store its ID in jQuery data
$this.data("loopId", setInterval(function () {
// only do something if we are still hovering
if ($this.data("isHovering")) {
$this.css("color", getRandomColorValue());
}
}, 100);
},
function () { /* mouseleave */
$this = $(this);
// take note that the mouse is no longer hovering
$this.data("isHovering", false);
// clear the interval that was set and delete the ID
if ($this.data("loopId")) {
clearInterval($this.data("loopId"));
$this.data("loopId", false);
}
}
)
changeColorTimerId = -1;
$('.box').hover(function(){
//mouseOver code here
changeColorTimerId = setInterval ( changeColor, 1000 );
},function(){
//mouseOut code here
if ( changeColorTimerId ){
clearInterval ( changeColorTimerId )
}
});
function changeColor(){
$(".box").css ( 'backgroundColor', '' + getRandomColor() );
}
function getRandomColor(){
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
working example here:
http://jsbin.com/etogi3/2