I'm creating a web game where the user types the code and the result is displayed on the screen, for Web Design classes. I've already made something to recognize HTML and CSS codes and now I'm trying with JavaScript. My problem is to execute JavaScript code. The first class is about variables.
I created a editable screen with a cursor where the user types the code:
The square is the cursor in input. I put the first part of code above the input and the score bellow just to show what is going to happen. The user insert his code (just a variable declaration) and press a submit button to test if is correct. What a tried to get the code and execute was:
$("#submit").on("click", function(){
var full_code = '$(document).ready(function() {'
+ $(".text").val()
+ 'setInterval(function() {ola.style.display = (ola.style.display == \'none\' ? \'\' : \'none\');}, 500);});';
console.log(full_code);
var functionJS = new Function(full_code);
functionJS();
});
In this example I just wanted to create a blinking animation. So I tried to get the previous code and append to user code and the rest of code to execute all the string as a function, but the part of the code: ola.style.display
is not working because it says that the variable ola is null. What user should types is like: var ola = document.getElementById("ola");
. What is wrong with the code? And is this the better way to do this?