简体   繁体   中英

Run a function if a button has ever been clicked, even on page reload

I have a button:

<script>
function never(){
alert('This is place holding text');
}
</script>
<button onclick="never()">Understood</button>

I need to use local storage or cookies to remember if the button has ever been clicked, and if it has, to run the function and if it hasn't to not run the function until they click the button, I've had an idea...

  1. Onload Run Function.
  2. Check if button has been clicked, then run function.
  3. Else do not run function.
  4. If button is clicked set cookie or value to run function automatically now.

I have no idea how to actually implement this though, or if this won't work. And yes, I know the real solution would be server side, but I do not have a server.

do u mean this way :

<button onclick="run()">Click</button>
function run(){
localStorage.setItem('item','value');
}

or something else ??

You can check this implementation

You can just store some value to localStorage when clicked and then read those values later.

HTML

<button id="btn">Click Me</button>

JavaScript

const btn = document.querySelector("#btn");

if(localStorage.getItem('clicked')) btn.innerText = 'clicked once';


btn.addEventListener('click', handleClick);

function handleClick(event) {
  if(localStorage.getItem('clicked')) return;
  else {
    localStorage.setItem('clicked', true);
    btn.innerText = 'clicked once';
  }
}

or try this way

 var someData = 'any data.'; localStorage.setItem('myData', '') function never(){ localStorage.setItem('myData', someData); alert('This is place holding text'); } var data = localStorage.getItem('myData'); if (data != ""){ never() } localStorage.removeItem('myData')
 <button onclick="never()">Understood</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM