javascript - Execute function only on first load, not on change -


i have page shows few products, sorting functionality.

i have function, examplefunction(), need run once. function @ top of javascript execution so:

<script>     examplefunction(); </script> 

but now, add sorting functionality, need run inside of sort, aswell, looks this:

$(".sort-products").change(function () {    // sort    // sort    // more sorting     examplefunction(); }); 

but problem here is, when sort, need reload page re-executes whole javascript, runs examplefunction() again. i'm looking for, , asking guys is, if there type of check can in original examplefunction() make sure runs on first reload. possible do?

you can use localstorage or sessionstorage this.

just add if condition inside examplefunction this

function examplefunction(){    //initially pageloaded in localstorage undefined     if(typeof (localstorage.pageloaded) === 'undefined'){       //all code needs run on 1 page refresh goes here       //now set localstorage value if condition false on page refresh       localstorage.pageloaded = true;     }  } 

and when close browser or tab delete localstorage value

window.onbeforeunload = function () {        localstorage.removeitem(pageloaded); } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -