Link to home
Start Free TrialLog in
Avatar of peter-cooper
peter-cooper

asked on

How do I run a function once

Hello
I have a function that works as I want. However, I would like it to run just once to show a message. I have tried to set a var to 0 then inc the var using ++ in the for loop but whatever I try, it just keeps displaying.

I would be grateful if someone could help with this. Thanks

<script type="text/javascript">
  window.onload = function() {
    var calendaricons = document.getElementsByClassName('jqx-icon-calendar');

    for (var i = 0; i < calendaricons.length; i++) {
      calendaricons[i].addEventListener('click', function() {
        notif({
          type: "info",
          msg: "<b>ERROR:<br /><br />You must enter a search term</b><p>Click cross to close</p>",
          width: 600,
          height: 99,
          multiline: true,
          position: "center",
          fade: true,
          //timeout: 3000,
          autohide: false,
          clickable: true
        });
      });
    }
  };
</script>

Open in new window

Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Check this. I create a var named counter outside of the scope window.onload function assign it with thye value 0.Via if icondition tyhe function is going to execute if the counter ===0.
var counter=0;
window.onload = function() {
    if(counter===0){
    var calendaricons = document.getElementsByClassName('jqx-icon-calendar');
    
    for (var i = 0; i < calendaricons.length; i++) {
      calendaricons[i].addEventListener('click', function() {
        notif({
          type: "info",
          msg: "<b>ERROR:<br /><br />You must enter a search term</b><p>Click cross to close</p>",
          width: 600,
          height: 99,
          multiline: true,
          position: "center",
          fade: true,
          //timeout: 3000,
          autohide: false,
          clickable: true
        });
      });
      counter++;
    }
    }else{
      return false;
    }
  };

Open in new window

Avatar of peter-cooper
peter-cooper

ASKER

@Leonidas Thanks for reply. However, the message is still displaying more than once. Also, by checking in console, 'counter++; console.log(counter);' I can see that the counter never increments but remains at 1. Thanks
You have right Peter because every time that the window load the var is going to be 0.There is another way to do using sessionsStorage or localStorage
One basic difference between  these two is the expiration time. Check the documentation. In the following code I am using sessionStotage property.

window.onload = function() {
    if(!sessionStorage.counter){
    sessionStorage.setItem('counter','one');
    var calendaricons = document.getElementsByClassName('jqx-icon-calendar');
    
    for (var i = 0; i < calendaricons.length; i++) {
      calendaricons[i].addEventListener('click', function() {
        notif({
          type: "info",
          msg: "<b>ERROR:<br /><br />You must enter a search term</b><p>Click cross to close</p>",
          width: 600,
          height: 99,
          multiline: true,
          position: "center",
          fade: true,
          //timeout: 3000,
          autohide: false,
          clickable: true
        });
      });
    }
    }else{
      sessionStorage.removeItem('counter'); 
      return false;
    }
  };

Open in new window

@leonidas Sorry, still displaying message. Thanks for heads up re sessionStorage.
Try with localStorage:
window.onload = function() {
    if(!localStorage.counter){
    localStorage.setItem('counter','one');
    var calendaricons = document.getElementsByClassName('jqx-icon-calendar');
    
    for (var i = 0; i < calendaricons.length; i++) {
      calendaricons[i].addEventListener('click', function() {
        notif({
          type: "info",
          msg: "<b>ERROR:<br /><br />You must enter a search term</b><p>Click cross to close</p>",
          width: 600,
          height: 99,
          multiline: true,
          position: "center",
          fade: true,
          //timeout: 3000,
          autohide: false,
          clickable: true
        });
      });
    }
    }else{       
      return false;
    }
  };

Open in new window


And sessionStorage like this:
window.onload = function() {
    if(!sessionStorage.counter){
    sessionStorage.setItem('counter','one');
    var calendaricons = document.getElementsByClassName('jqx-icon-calendar');
    
    for (var i = 0; i < calendaricons.length; i++) {
      calendaricons[i].addEventListener('click', function() {
        notif({
          type: "info",
          msg: "<b>ERROR:<br /><br />You must enter a search term</b><p>Click cross to close</p>",
          width: 600,
          height: 99,
          multiline: true,
          position: "center",
          fade: true,
          //timeout: 3000,
          autohide: false,
          clickable: true
        });
      });
    }
    }else{
      
      return false;
    }
  };

Open in new window

@Leonidas Still the same. I did a console.log for rhe session code and it returned this is it helps. 1 item in Storage counter="one"
It's weird. Check the following code. The second time that window.onload happens the console log it is not must executing:
window.onload = function() {
    if(!sessionStorage.counter){
    sessionStorage.setItem('counter','one');
    console.log('Function Executed');
    }else{
      
      return false;
    }
  };

Open in new window

Isn't that what should happen on window.load? when you first load the window it will be 0? in the above code you are saying on window.load make 0 if 0 then make 1? But we need to inc on click event so the counter will always be greater than 1 to disable the message. Thanks
@Leonidas Managed to sort it like so:

<script type="text/javascript">
  var counter = 0;

  window.onload = function() {
    var calendaricons = document.getElementsByClassName('jqx-icon-calendar');

    for (var i = 0; i < calendaricons.length; i++) {
      calendaricons[i].addEventListener('click', function() {
        if (counter === 0) {
          notif({
            type: "info",
            msg: "<b>ERROR:<br /><br />You must enter a search term</b><p>Click cross to close</p>",
            width: 600,
            height: 99,
            multiline: true,
            position: "center",
            fade: true,
            //timeout: 3000,
            autohide: false,
            clickable: true
          });
          counter++;
        } else {
          return false;
        }
      });
    }
  }
</script>

Open in new window

@leonidas. haha Got there in the end. Thanks very much for your help.
ASKER CERTIFIED SOLUTION
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@leonidas. For some reson this didn't award points and put in a close request. I have raised a request attention and once moderator actions this I shall award points to you. Thanks
Actioned in error. Points should have been awarded.
Actioned in error. Should have awarded points to participant.
I hope to helped hahahah.I didn't understand  at the beginning the problem. Have a nice summer day from Greece!!!!
Hope this works this time. Thanks once again
No chance in the UK haha. Have a good day.