jQuery .click function not work after reload

168 Views Asked by At

I use jQuery on my website to add a new class and remove the other, but after a reload of the page, the new class disappears.

Code:

$(document).ready(function() {
    $('#list').click(function(event){event.preventDefault();$('.viewgrid').addClass('viewlist');$('.viewgrid').removeClass('viewgrid');});
    $('#grid').click(function(event){event.preventDefault();$('.viewlist').addClass('viewgrid');$('.viewlist').removeClass('viewlist');});
}); 

How do I keep the modification?

1

There are 1 best solutions below

16
pixelarbeit On

jQuery is a framework for javascript which is running client side within your browser. If you don't save your changes in the file, the changes will only be temporary.

EDIT: You need to load the state on siteload:

var def = 'viewlist';
var view = Cookies.get('view') || def;

$('#view').addClass(view);

And save it on a click on the button:

Cookies.set('view', 'viewlist');

I wrote this little codepen for you: http://codepen.io/anon/pen/oBezzz

Notice that I used the JS plugin JavaScript Cookie. You need to download it and include it into your head section.