Skip to content

Instantly share code, notes, and snippets.

@klauskpm
Last active October 30, 2020 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klauskpm/f72a7a067e50731d66e27ecbb5500ea4 to your computer and use it in GitHub Desktop.
Save klauskpm/f72a7a067e50731d66e27ecbb5500ea4 to your computer and use it in GitHub Desktop.
(function () {
var Contrast = {
storage: 'contrastState',
cssClass: 'contrast',
currentState: null,
check: checkContrast,
getState: getContrastState,
setState: setContrastState,
toogle: toogleContrast,
updateView: updateViewContrast
};
window.toggleContrast = function () { Contrast.toogle(); };
Contrast.check();
function checkContrast() {
this.updateView();
}
function getContrastState() {
return localStorage.getItem(this.storage) === 'true';
}
function setContrastState(state) {
localStorage.setItem(this.storage, '' + state);
this.currentState = state;
this.updateView();
}
function updateViewContrast() {
var body = document.body;
if (!body) return;
if (this.currentState === null)
this.currentState = this.getState();
if (this.currentState)
body.classList.add(this.cssClass);
else
body.classList.remove(this.cssClass);
}
function toogleContrast() {
this.setState(!this.currentState);
}
})();
@ricardolino
Copy link

ricardolino commented Jun 2, 2017

Na linha 32:

var body = document.getElementsByTagName('body')[0]; // Poderia ser: var body = document.body;

@klauskpm
Copy link
Author

klauskpm commented Jun 2, 2017

Obrigado @ricardolino. Alteração feita.

@auredfreitas
Copy link

Prezado, estava ocorrendo o erro abaixo ao carregar a página, mas mesmo assim não deixava de funcionar o contraste. Para retirar o erro faço um teste antes na função updateViewContrast para verificar se o body é diferente de NULL.

Uncaught TypeError: Cannot read property 'classList' of null
at Object.updateViewContrast [as updateView] (custom.js:57)
at Object.checkContrast [as check] (custom.js:35)
at custom.js:32
at custom.js:63

function updateViewContrast() {
var body = document.body;
if (body !== null) {
if (this.currentState === null)
this.currentState = this.getState();

if (this.currentState)
    body.classList.add(this.cssClass);
else
    body.classList.remove(this.cssClass);

}
}

@klauskpm
Copy link
Author

Obrigado @auredfreitas. Alteração feita.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment