Allow the user to type the javascript code that is then run in the browser

advertisements

I am wanting to build some simple modules to help my students learn javascript. I have made a set of functions that I would like for the student to be able to enter and then that function be executed. For example. I have a function that moves an image from 1 div to another called move(); I then have a text field where the user needs to type move(); When they click submit I want the code they wrote to be executed so they can see what it does.

I had a really hard time searching for this and was hoping someone could point me in the right direction. Thanks!

<body>
    <textarea id='userInput'></textarea>
    <div id='go'>Go</div>
    <div id='canvas'>
        <div id='r1c1' class='square'><img src='dog.png' id='dog'></div>
        <div id='r1c2' class='square'></div>
    </div>
</body>
</html>
    <script>
    $('document').ready(function(){
    $('#go').click(function(){
        var code = $('#userInput').val();
        EXECUTE code; //This is where I want the code to be executed//
    });
});

function move(){
    $('#dog').appendTo('#r1c2');
};


You can use eval() for this purpose (on w3Schools)

To take this even further, you can wrap the code in a try catch block to handle user errors.