I have a javascript function that makes assigned text alternate between 2 colors, gray, and the color value I set when I run the function.
Here is the code I use. The function:
function flashtext(ele,col) {
var tmpColCheck = document.getElementById( ele ).style.color;
if (tmpColCheck === 'gray') {
document.getElementById( ele ).style.color = col;
} else {
document.getElementById( ele ).style.color = 'gray';
}
}
Then for each unique flash I do (content is generated on the fly):
setInterval(function() {
flashtext('flashingtext1','#ffffff');
}, 500 );
The number flashingtext, flashingtext2 increments with each one added, and the color is set to the color it’ll alternate with, in this case white.
Then
<span id='flashingtext2'>flash me</span>
Is there any way I could trim this whole code down so I don’t have to add new javascript for each instance that occurs. So i can just have the function down, then define the rest in the span tag? Something like
<span id=flashingtext data=#ffffff> flash white </span>
The color I give always alternates between that and gray
Basically, cut out the middle bit.
Note: Using jquery too if that gives an easier way.
If you want the same code to apply to all instances then give the elements a common class, say “flashingtext”, so that you can select them as a group, but set the individual colours with an inline style:
Then have a “gray” class:
Which uses
!importantso it can override the inline styles.Then your function can select all elements that have that “flashingtext” class and toggle “gray” on or off:
Demo: http://jsfiddle.net/yenK9/
If you need to assign an
idto the spans so that you can select them individually for some other purpose then go ahead, but for this colour thing you don’t need to.