Witajcie,
Potrzebuję zrobić następującą funkcjonalność:
- na stronie jest link, po kliknięciu którego będzie dodawana do body klasa hightcontrast - i po ponownym kliknięciu będzie ona usuwana.

Dotychczas zrobiłem taki kod:

  1.  
  2. <a href="#" title="Zmień kontrast" class="float-right m-0 pr-2 contrast">
  3. <img src="assets/images/ikon1.png" class="img-responsive contrast" alt="Zmień kontrast">
  4. </a>
  5.  
  6.  
  7. $(document).ready(function($) {
  8. if (localStorage.getItem("contrast") === null) {
  9. localStorage.setItem("contrast", '1');
  10. }
  11.  
  12. if (typeof(Storage) !== "undefined") {
  13. // checkContrast();
  14.  
  15. function checkContrast() {
  16. let oldContrast = localStorage.getItem("contrast");
  17. alert(oldContrast);
  18. updateViewContrast(oldContrast);
  19. }
  20.  
  21. $(".contrast").click(function() {
  22. checkContrast();
  23. });
  24.  
  25. function updateViewContrast(contrastVersion) {
  26. if (contrastVersion === '1') { // normalny
  27. $("body").removeClass('highcontrast');
  28. localStorage.setItem("contrast", '2');
  29. } else {
  30. $("body").addClass('highcontrast');
  31. localStorage.setItem("contrast", '1');
  32. }
  33. }
  34. }
  35. });
  36.  


Po każdym kliknięciu wyświetlam alert z 1 lub 2 aby zobaczyć czy działa.

Problem w tym że po kliknięciu w linka widzę 2 alert (jeden po drugim): 1, 2.

Klasa highcontrast po pierwszym kliknięciu jest widoczna cały czas.

Jak to naprawić?


Bardzo proszę o pomoc