Jump to content

set cookie via javascript


ngrmm
 Share

Recommended Posts

My clients wants a modal to show up on every page. But when a user clicks inside the modal -> a session-cookie is set and the modal gets a class.

// user clicks on modal button
$('.modal_button').click(function(){

	// 1. set PW session cookie
	
	// 2. toggle class
	$('.modal').toggleClass('off');

});

I know how to set a cookie on page-load via PW-API. But the click on the modal button does not force a page-load. So i have to set the cookie through javascript. Is there a way to do that?

Link to comment
Share on other sites

You can't save data to the session in the browser, because session data is stored server-side. The only thing the browser stores regarding the session is the cookie that identifies the current session for the server. If you need to access the stored value both client- and server-side, you can just use a regular cookie. By omitting the expires field it will only be valid for the current browser session, the same as ProcessWire's sessions.

However, if you don't need to access the value server-side (which I assume you don't for a modal), you can use sessionStorage or localStorage instead, which do the same thing as cookies but with a cleaner API. Use localStorage if you want the stored value to persist across sessions (for a dismissable modal this is probably what you want) or sessionStorage to store a value only for the current browser session.

const dismissalKey = 'modal-dismissed';

// user clicks on modal button
$('.modal_button').click(function(){

	// 1. store dismissal in the sessionStorage OR the localStorage
    localStorage.setItem(dismissalKey, '1');
  
	// 2. toggle class
	$('.modal').toggleClass('off');

});

// somewhere else, check if the modal has been dismissed
const modalIsDismissed = Boolean(localStorage.getItem(dismissalKey));

 

  • Like 1
Link to comment
Share on other sites

3 minutes ago, MoritzLost said:

@ngrmm Yes, you can set regular cookies as mentioned in my first paragraph, though they won't be accessible through ProcessWire's $session API.

But why would you load 87kB of library bloat for something that you can do in one line? 🙂

you're right. I'll use the localStorage and hide/minify the modal with js/css if modal is dismissed.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...