Click here to Skip to main content
15,400,433 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
below is my javascript function, it needs to run only once. It means when the user visits the website for the first time only the code must be run when the page reloads it doesn't need to run This is my problem, kindly check and provide your answers. I am running this code in WordPress using a custom HTML plugin.


JavaScript
<pre>

<head>

<link rel="stylesheet" href="https://unpkg.com/intro.js/minified/introjs.min.css">
<script src="https://unpkg.com/intro.js/minified/intro.min.js"></script>

</head>

<body>
<script>
var invoke_introJs​ = true;  
introJs().setOptions({
  if(invoke_introJs){
  steps: [{
    intro: "Welcome to our website!"
  }, {
    title: 'Introducing New Dark Mode',
    element: document.querySelector('.menu-main-container'),
    intro: "Now you can browse in dark mode or dark theme!"
  }]
  }
}).start();
  </script>
</body>


What I have tried:

<script>
var invoke_introJs​ = true;  
introJs().setOptions({
  if(invoke_introJs){
  steps: [{
    intro: "Welcome to our website!"
  }, {
    title: 'Introducing New Dark Mode',
    element: document.querySelector('.menu-main-container'),
    intro: "Now you can browse in dark mode or dark theme!"
  }]
  }
}).start();
  </script>
Posted
Updated 17-Aug-21 4:26am

Use local storage to store a flag indicating that the code has run. Then test that flag when your page loads to see if it has already run.
JavaScript
const hasRunIntro = localStorage.getItem("hasRunIntro");
if (hasRunIntro !== "1"){
    // Run the intro...
    localStorage.setItem("hasRunIntro", "1");
}
Window.localStorage - Web APIs | MDN[^]
   
Comments
Havishka Halangoda 17-Aug-21 10:27am
   
@localStorage Property works
<script>
if (!localStorage.getItem('didRunIntro')) {
//Getting in here only when didRunIntro = false
introJs()
    .setOptions({
        steps: [
            {
                intro: 'Welcome to our website!',
            },
            {
                title: 'Introducing New Dark Mode',
                element: document.querySelector('.menu-main-container'),
                intro: 'Now you can browse in dark mode or dark theme!',
            },
        ],
    })
    .start();

//Change the value to true to avoid more runs
localStorage.setItem('didRunIntro', true);
}
  </script>
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900