Change Table Row background color on Timer Event using jquery
I basically have this markup coming from my JSP. I add class in each row and I want have a blinking effect on each row.
<table>
<tbody>
<tr class="blinkYellow">
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
</tr>
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
</tr>
<tr class="blinkYellow">
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
</tr>
</tbody>
</table>
I setup a Jquery function and a timer like below. But I am currently unsure why the background-color of the table did not change.
$(document).ready(function(){
setInterval(findYellow,1000);
function findYellow(){
$("tr.blinkYellow").each(function(){
if($(this).attr("background-color") == "yellow"){
$(this).attr("background-color", "white")
}else{
$(this).attr("background-color", "yellow")
}
})
}
});
I check out the Firebug HTML Tab and I notice that the background-color is really being changed on the selected element row.
But I am not sure why the background color of the row is not togg开发者_JS百科ling its color from yellow and white.
Wouldn't it be better to use css classes to add the color. If you do so, you can use jquery as follows:
$(this).toggleClass("blink-yellow");
EDIT:
You can use this page for trying out such things... http://jsfiddle.net/rgkQK/3/
$(document).ready(function(){
setInterval(findYellow,1000);
function findYellow(){
$("tr.blinkYellow").each(function(){
$(this).toggleClass("background-color-yellow");
})
}
});
In fiddle it looks like it would work quite well ;-)
The attr
function will add/change an attribute. Use the css
function instead of the attr
function.
$(document).ready(function(){
setInterval(findYellow,1000);
function findYellow(){
$("tr.blinkYellow").each(function(){
var $this = $(this);
if($this.css("background-color") == "yellow"){
$this.css("background-color", "white")
}else{
$this.css("background-color", "yellow")
}
})
}
});
Another option would be to set a css style for the blinkYellow
class that includes a background-color
of yellow, and then toggle it:
var $blinkYellow = $("tr.blinkYellow");
$(document).ready(function(){
setInterval(findYellow, 1000);
function findYellow() {
$blinkYellow.each(function() {
// note: jQuery is not really needed here - instead, you could use the following line
// this.className = this.className == 'blinkYellow' ? '' : 'blinkYellow';
$(this).toggleClass('blinkYellow');
});
}
});
精彩评论