views:

58

answers:

3

Hello friends, I am wondering if my jquery function is correct

<script>
window.blinker = setInterval(function(){
  if(window.alerta){
    $('a.cadastrotopo').css('color','#346698');
    $('a.cadastrotopo').css('text-decoration','underline');
      window.alerta=false;
    }
    else{
      $('a.cadastrotopo').css('color','#000');
      $('a.cadastrotopo').css('text-decoration','none');
      window.alerta = true;
    }
},500);
</script>

is working ok, but I wonder if I'm doing the right way.

I thank you.

+9  A: 

Personally I would use CSS more, particularly classes:

a.cadostropo {
  color: #000;
  text-decoration: none;
}
a.alert { 
  color: #346698;
  text-decoration: underline;
}

and then the solution becomes trivial:

setInterval(toggleAlert, 500);

function toggleAlert() {
  $("a.cadostropo").toggleClass("alert");
}

One side note: instead of multiple css() calls you can use anonymous objects to specify multiple properties.

$("a.cadostropo").css({color: "#346698", textDecoration: "underline"});

That being said, I prefer not to use hardcoded CSS manipulation like this. Favour classes. They're far more flexible and you don't have to worry about destructive changes and rolling them back.

cletus
Perfect. Fwiw, if 'window.alerta' is somehow important beyond the scope of the immediate function then 'window.alerta = !window.alerta;' would be preferable to the if/else.
annakata
A: 

Yes, you are, although you could combine the css declarations to look like this.

.css({'color' : "#346698", 'text-decoration' : "underline"});
phoffer
cletus's version would be more efficient, as it would remove the if statement. Mine would just be better if you needed to do something other than a simple toggle (i.e. somewhere else in your code)
phoffer
Cletus is right, it is much better to use classes
phoffer
A: 

Thanks friends, the two forms worked perfectly!

Thanks

Patrique
This is not an answer. Please use the comments feature when appropriate.
Álvaro G. Vicario