Raffy T Lawrence Raffy T Lawrence - 3 months ago 30
Javascript Question

Javascript: Store function in localstorage

Is this possible to insert to localstorage or is there other way to store this?

$('#pass_to_score').on('click',function(){

var compressed = function(){
$('.whole_wrap_of_editcriteria').css('display','none');
$('#wrappler').css('display','block');
$('#li_addcriteria').css('display','none');
$('#li_menu1').addClass('active');
$('#home').removeClass('active');
$('#menu1').addClass('active');
$('#title_panel').html('Edit criteria scoring');
}
compressed();
localStorage.setItem('compressed', compressed());
//i also try set as JSON.stringify but its undefined

});

Answer

I don't know why you'd want that, I would not recommend it, but you can do it using toString.

Store it:

var compressed = function (){
  alert('Hello world!');
};

// Store it as a String
localStorage.setItem('compressed', compressed.toString());

Later, retrieve it:

var compressedString = localStorage.getItem('compressed');

// Convert the String back to a function
var compressed = eval(compressedString);
Comments