Change CSS with Jquery

2

How do I get the user to click on a particular link, change the CSS and the title? For example:

I have this link: Contraste

By clicking on it, change the CSS and the name of the link too, going to Sem contraste .

I started doing something, but JQuery is not my strong. See below:

<a href="#" id="contraste" class="ativar" style="font-weight: bold" accesskey="c" title="Contraste ALT + c">Contraste (c)</a>

    $('#contraste').click(function(){

      var acao = $(this.className);

        if(acao === "ativar"){
           // Alterar o CSS
          }else{
            // Voltar para o CSS atual
        }

    });
    
asked by anonymous 05.05.2018 / 15:06

2 answers

1

A very simple solution is to use the toggleClass function, which places the class in case it is not there, or takes a case already have For this reason you will toggle between having the CSS of the class and not having it, working exactly as you want. The link text must already be switched separately, it is still only a if .

Example:

$('#contraste').click(function(){
  $(".conteudo").toggleClass("contraste"); //coloca ou retira a classe contraste
  //troca o texto do link
  $(this).text($(this).text() == "Contraste (c)" ? "Sem Contraste (c)": "Contraste (c)");
});
.conteudo {
  background-color:lightGray;
  width:300px;
  height:100px;
}

.contraste {
  background-color:darkGray;
  color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ahref="#" id="contraste" accesskey="c" title="Contraste ALT + c">Contraste (c)</a>
<div class="conteudo">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse feugiat, lorem vitae consectetur tincidunt, nisl erat porta ligula, et scelerisque elit lorem nec augue.
</div>
    
05.05.2018 / 15:46
2

You can check if the link contains the class with the .is method:

$('#contraste').click(function(){

   var acao = $(this).is(".ativar"); // retorna true ou false

   if(acao){ // se for true
      $(this)
      .css({ // muda o CSS
         "font-weight": "normal"
      })
      .text("Sem contraste") // altera o texto
      .removeClass("ativar"); // remove a classe
   }else{ // se for false
      $(this)
      .css({ // muda o CSS
         "font-weight": "bold"
      })
      .text("Contraste (c)") // altera o texto
      .addClass("ativar"); // adiciona a classe
   }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ahref="#" id="contraste" class="ativar" style="font-weight: bold" accesskey="c" title="Contraste ALT + c">Contraste (c)</a>
    
05.05.2018 / 15:31