Search code examples
javascriptfunctionvar

Change a variable or call a function through text in JS?


This is probably a strange request so I'll get straight to the point.

Is it possible to call a function through text? For example, if I was to type "themechange" on my website in a text box, I then use that information to call the function I want?

Additionally, is it possible to do the same with variables? So, I type "textcolour red", do .split after storing it itself in a variable, and then use that to go "word[0] = word1" through functions on the back end?

I've already done something similar by using root, but I want it to be more expandable than JUST root variables. enter image description here

var function1 = undefined, function2 = undefined, function3 = undefined, function4 = undefined, function5 = undefined;
var array = consolein.split(' '), function1 = array[0], function2 = array[1], function3 = array[2], function4 = array[3], function5 = array[4];
function text(){
   if (function1 == "custom"){
      if( function2 == "console"){
         if (function3 == "background"){
            inprompt = inprompt + "Background color set to: " + function4; println(); println();
            consoleback = function4; docelem.style.setProperty('--consoleback', consoleback)
         }
      }
   }
}

Thanks in advance.


Solution

  • Yes it is possible to do that with Javascript. It is actually something interesting and I wanted to do it before.

    This is just a small example. You just make a list of commands and then make some rules how to run a command, in this case. You can print a word, by typing print or change the background color: bgColor

    var input = document.getElementById("myInput");
    var commandList = {
        print: function (command) {console.log(command[1])},
        bgColor: function (command) {input.style.backgroundColor = command[1]}
    }
    
    
    function run(command) {
        commandList[command[0]](command);
    }
    
    input.addEventListener("keyup", function(event) {
      if (event.keyCode === 13) {
          var command = input.value.split(' ');
          run (command)
      }
    });
    <input type="text" id="myInput">