Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Jquery slideDown only once per session

The function below shows a notification toolbar when the user visits a page. The toolbar slides down from the top of the window, pushing down the page content.

This is OK, but the effect becomes annoying when visiting more pages. What I am trying to accomplish: slide down the notification toolbar only the first time the user interacts with the site. After the notification is first displayed, if the user refreshes the page or visits other site pages, the notification toolbar is shown instantly, with no slide down effect.

I should probably use SessionStorage for this, just don't exactly how.

$(function(){
$('#notification_toolbar').slideDown();
});
like image 507
Malasorte Avatar asked Mar 15 '23 10:03

Malasorte


2 Answers

Since you've already mentioned sessionStorage, it's pretty easy to use it to save a flag that tells you if the slideDown already happened or not. Then you can use that flag to make sure it doesn't happen again.

Inside you slide down code:

// perform the slide down only if the slide down flag wasn't set
if(sessionStorage.getItem('hasSlideDown') !== 'yes') {  // check if slide down flag was set
    sessionStorage.setItem('hasSlideDown', 'yes');      // set the slide down flag
    $('#notification_toolbar').slideDown();             // perform the slide down
} 

How sessionStorage works:

A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

like image 104
nem035 Avatar answered Mar 20 '23 03:03

nem035


You need to persist information that slide animation was already performed, and in your code you need to put conditional like

if (skipAnimation) {
  # put your code to show toolbar without slide animation here
}

You can achive that in many ways: using url querystring (append ?skipAnimation=true to your address) or by using your session storage. Querystring would be easiest, as you can easily read it with jquery. Session storage would give your users better experience.

like image 45
Fisher Avatar answered Mar 20 '23 03:03

Fisher