Search code examples
jquerycsshyperlinkblink

My jquery this correct?


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.


Solution

  • 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.