How to apply permanently the jQuery addClass method even the page has reloaded the class added remains. Thankyou in advance for the answers.
Asked
Active
Viewed 507 times
1
-
Since javascript is client-side and the html page is located on the server, the only chance to achieve this would be to do an ajax request and save the class names of your element somewhere, in a database for example. The next time the page reloads, all the class names of the database will be applied to that element. – elementzero23 Jan 26 '17 at 06:51
-
you can use cookie, if you want to refer something to be present in there – Drixson Oseña Jan 26 '17 at 06:56
-
@elementzero23 thankyou for the answer, is there any solutions? here is what I want to do is a theme for my page, which is the user can select what color/themes they want to by selecting from my menu and it will be applied permanently even the page reloaded. thanks – Renzo Jan 26 '17 at 07:00
-
@Renzo this is a typical scenario where you would use cookies/local storage – elementzero23 Jan 26 '17 at 07:23
1 Answers
0
As one of the comments already noted: javascript is running client side in most use cases (And if you are using jQuery you are probably not using some fancy js ssr). So you probably should output the class based on some state. The way to do this is either save state in the server via an ajax call or save state in the client browser via cookie, localstorage, sessionstorage etc. Here is a link to a SO question about reading/writing cookies with jQuery So in the method calling addClass you can save the cookie with the class set, and in $ready()
function check the cookie and apply the class accordingly on page load
-
is there any solutions? here is what I want to do is a theme for my page, which is the user can select what color/themes they want to by selecting from my menu and it will be applied permanently even the page reloaded. thanks – Renzo Jan 26 '17 at 07:03
-
@Renzo I specified the different solutions in my answer. I'll add a link for an example using jquery and cookies, but really how to solve state persistence is up to you – alonisser Jan 26 '17 at 07:08