Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Run once per session

I have a function that is triggered by "Calculate" button

I need this line to only run once per session (session could be 1 day or until browser is reloaded).

$('.popup-with-form').magnificPopup('open');

This opens a Magnific Popup. Once this function is executed (popup opens), if "calculate" button is pressed again, I don't want popup to open again.

JS / JQuery code:

function StateChanged() {
       if (XmlHttp.readyState == 4 || XmlHttp.readyState == "complete") {
           $('.popup-with-form').magnificPopup('open');
          document.getElementById("CalcSum").innerHTML = XmlHttp.responseText;
          document.getElementById("CalcSumPopup").innerHTML = XmlHttp.responseText;
       }
    }

PS I know many of these questions pop up, and I tried different ways of doing thing, but since I'm "code-challanged" and do not know JQuery or JS I can't figure it out. I know there is a .one "thing" in JQuery, but don't understand how to make it work.

like image 555
Levchik Avatar asked Aug 01 '14 00:08

Levchik


2 Answers

If you want to execute this line only once per browser session you can use sessionStorage. When you set a variable on sessionStorage it keeps its value until the browser closes (e.g. until you close Google Chrome).

So you can do something like:

if (!sessionStorage.alreadyClicked) {
    $('.popup-with-form').magnificPopup('open');
    sessionStorage.alreadyClicked = 1;
}

Be careful with sessionStorage because it can only store string values.

If you want the line to be executed only once per page session (which means once every page refresh) then you can use any variable and set it to true to remember you already executed the line:

if (!window.alreadyClicked) {
    $('.popup-with-form').magnificPopup('open');
    alreadyClicked = true;
}
like image 166
Marco Bonelli Avatar answered Nov 08 '22 08:11

Marco Bonelli


Try

Edit, v2

I read about .one but could not figure it out :( ... I actually need it to run once ONLY when CALCULATE button is pressed. – Roofing Calculator

html

<!--  removed `action="javascript:GetInfo();"
              , accept-charset="UNKNOWN"
              , enctype="application/x-www-form-urlencoded" 
              , method="post"` 
      from `form` attributes -->
<form id="formcalc" style="text-align: left;">    
    <!-- changed `input` `type` to `button` -->
    <input name="calculate" type="button" value="Calculate" />
</form>

js

$("#formcalc > input[name='calculate']")
.one("click", function(e) {
  e.stopPropagation();
  GetInfo();
});

v1

$("a.popup-with-form").one("click", function(e) {
  // do stuff, once
  // i.e.g., 
  // `XmlHttp.onreadystatechange = StateChanged;` at `ShowSum()`
  $(e.target).remove(); // remove element when `click`ed once
});

jsfiddle http://jsfiddle.net/guest271314/7K3tn/

See http://api.jquery.com/one/

like image 43
guest271314 Avatar answered Nov 08 '22 06:11

guest271314