RyanY
RyanY

Reputation: 665

Allow user to type javascript code that is then executed in browser

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');
};

Upvotes: 2

Views: 849

Answers (2)

Adam Zuckerman
Adam Zuckerman

Reputation: 1641

You can also use the console with most browsers to execute javascript. Hit F12 to load up the developer tools on all of the browsers. Click on the console tab. Type javascript until your heart's content.

One advantage to this method is that you should be able to execute any code that is included on the page.

Upvotes: 0

Odys
Odys

Reputation: 9090

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.

Upvotes: 1

Related Questions