skip to Main Content

Below is my JavaScript function, it needs to run only once. It means that when the user visits the website for the first time the code must be run. When the page reloads it doesn’t need to run. I am running this code in WordPress using a custom HTML plugin.

<script>
    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();
</script>

2

Answers


  1. As ivar noted, cookies are send with every request, so I would recommend to use the localStorage approach, given by Or Partush
    Will leave the answer for the sake of completion.

    You could use cookies to make sure your code is only executed once.

    function isCookieSet () {
        const cookieValue = document.cookie
            .split('; ')
            .find(row => row.startsWith('cookie1'))
            .split('=')[1];
        return cookieValue;
    }
    
    function init() {
        if(!isCookieSet()) {
            // execute your code
            // set cookie
            document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
        }
    }
    

    Something like this, see also https://developer.mozilla.org/en-US/docs/Web/API/document/cookie#example_2_get_a_sample_cookie_named_test2

    You could also write a helper function to easily set and get cookies as shown here: Set cookie and get cookie with JavaScript

    Login or Signup to reply.
  2. You can store a key like didRunIntro in localStorage initialized as false and run the script if didRunIntro is false.

    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);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search