Saving CSS class in object in localstorage on reload page

What I would like to do is preserve the CSS style when the user refreshes the page. This is my jQuery code:

$(function() {

$("#slider").draggable({
    axis: 'x',
    containment: 'parent',
    drag: function(event, ui) {
        if (ui.position.left > 230) {
            $("#well").fadeOut();
            $( "#well" ).addClass( "disappear" );
        } else {
            // Apparently Safari isn't allowing partial opacity on text with background clip? Not sure.
            // $("h2 span").css("opacity", 100 - (ui.position.left / 5))
        }
    },
    stop: function(event, ui) {
        if (ui.position.left < 231) {
            $(this).animate({
                left: 0
            })
        }
    }
});

$('#slider')[0].addEventListener('touchmove', function(event) {
    event.preventDefault();
    var el = event.target;
    var touch = event.touches[0];
    curX = touch.pageX - this.offsetLeft - 73;
    if(curX <= 0) return;
    if(curX > 230){
        $('#well').fadeOut();
    }
    el.style.webkitTransform = 'translateX(' + curX + 'px)'; 
}, false);

$('#slider')[0].addEventListener('touchend', function(event) {  
    this.style.webkitTransition = '-webkit-transform 0.3s ease-in';
    this.addEventListener( 'webkitTransitionEnd', function( event ) { this.style.webkitTransition = 'none'; }, false );
    this.style.webkitTransform = 'translateX(0px)';
}, false);

});

When the class “disappears” is added, I would like to add it even if the page reloads. I found a useful post here , but since I'm new to Javascript, I'm not sure how to use it in my case, and I would be very happy if someone could give me an individual answer.

Thanks in advance!

+1
source share
2 answers

After $( "#well" ).addClass( "disappear" );add

localStorage['wellClass'] = 'disappear';

And in the line below $(function() {add

previousWellClass = localStorage['wellClass'];
if (previousWellClass) $('#well').addClass(previousWellClass); 
0

.

var setClass = JSON.parse(localStorage.getItem('setClass')) || {};
$.each(setClass, function () {
    $(this.selector).addClass(this.className);
});
var addClassToLocalStorage = function(selector, className) {
    setClass[selector + ':' + className] = {
        selector: selector,
        className: className
    };
    localStorage.setItem('setClass', JSON.stringify(setClass));
};
var removeClassFromLocalStorage = function(selector, className) {
    delete setClass[selector + ':' + className];
    localStorage.setItem('setClass', JSON.stringify(setClass));
};

:

$("#well").fadeOut();
$("#well").addClass("disappear");
addClassToLocalStorage('#well', 'disappear');
// remove it removeClassFromLocalStorage('#well', 'disappear');

FIDDLE

, .

0

Source: https://habr.com/ru/post/1534770/


All Articles