VJS
VJS

Reputation: 2951

java scripts : events configurable

Below is my javascript :

My requirement is that I need to make events configurable ( comma separated ) like configurable interval. How will i do it.Plz suggest.

like var events_list=mousedown,mousemove,scroll

var interval = 7000;
    function Init () {
        if (document.addEventListener) {  
            document.addEventListener ("mousedown", function () {ChangeState ()}, false);
            document.addEventListener ("mouseup", function () {ChangeState ()}, false);
            document.addEventListener ("mousemove", function () {ChangeState ()}, false);
            document.addEventListener ("keydown", function () { ChangeState ()}, false);
           document.addEventListener ("scroll", function () {ChangeState ()}, false);
        }
    }
    setInterval(function(){        
    myFunction();},interval);
}

Upvotes: 0

Views: 61

Answers (1)

Kaizo
Kaizo

Reputation: 4185

Exactly what you want is not possible:

var events_list = mousedown,mousemove,scroll

In your example mousedown, mousemove and scroll will be considered variables and will throw an error because they are not declared. You can make them configurable as a list of elements in a string separed by comma:

var events_list = "mousedown,mousemove,scroll";

Then split them into an array and loop through it:

function Init () {
    var events_list = "mousedown,mousemove,scroll";
    if (document.addEventListener) {  
        events_list.split(',').forEach(function (eventName) {
          document.addEventListener(eventName, function () {
              ChangeState();
          }, false);
        });
    }
}

Upvotes: 1

Related Questions