Localstorage, jquery and CSS

Asked

Viewed 16 times

0

I’m saving the font size on localStorage and recovering to set after the page is ready, I am not able to set using the value recovered in localstorage, to set the source I am using jquery, follow code

Assim não funciona
$( document ).ready(function() {
// font size
var $elemento = $(".verseTextP");
var fontSize = window.localStorage.getItem('fontSize');
alert(fontSize)
$elemento.css('font-size', fontSize);  
});
Assim funciona
$( document ).ready(function() {
// font size
var $elemento = $(".verseTextP");
var fontSize = window.localStorage.getItem('fontSize');
alert(fontSize)
$elemento.css('font-size', 25);  
});

The alert is to show that the value is saved in localStorage and I can get the value right, which is the problem, because it doesn’t work if you use the value from a locaStorage.getItem?

inserir a descrição da imagem aqui

1 answer

1


You are trying to use the value of localstorage as a number, it turns out it is not garated that, you need to convert, or add the unit of measure if the value is string.

var fontSize = window.localStorage.getItem('fontSize'); 
alert(typeof fontSize); // verifique, deve ser string
$elemento.css('font-size', Number(fontSize));  //aqui garante um número
$elemento.css('font-size', fontSize + "px"); // ou adicione a unidade de medida px,pt,em, etc

  • Perfect guy! Thank you so much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.