User Inputed jQuery
by wrxsti85
HTML
<p><b>Objective:</b> Animate the black box with the ID #testBox to the right of the screen.</p>
<p><b>Enter code here:</b></p>
<textarea id="codeInput">$('#testBox').move('up');</textarea>
<button id="update">Update</button>
<div id="testBox"></div>
CSS
#codeInput {
width:100%;
height: 200px;
}
#testBox {
width:100px;
height:100px;
background: #000;
position:relative;
}
JavaScript
$('#update').click(function() {
// Define User Inputed Code
var userCode = $('#codeInput').val();
// Define Selector
var sel1 = userCode.indexOf("$('");
var sel2 = userCode.indexOf("').");
var selector = userCode.substring(0, sel1) + '' + userCode.substring(3, sel2);
// Define Method
var noSel1 = userCode.replace(selector, '');
var noSel2 = noSel1.replace("$('')", '');
var meth1 = noSel2.indexOf(".");
var meth2 = noSel2.indexOf("(");
var method = noSel2.substring(0, meth1) + '' + noSel2.substring(1, meth2);
// Define Attributes
var noMeth = noSel2.replace('.' + method, '');
var attrib1 = noMeth.indexOf("('");
var attrib2 = noMeth.indexOf("')");
var attrib = noMeth.substring(0, attrib1) + '' + noMeth.substring(1, attrib2);
var attributes = attrib.replace(/'/g, '');
// Check Method
if (method == 'shoot') {
alert('You shot at ' + selector);
}
if (method == 'move') {
if (attributes == 'up') {
$(selector).animate({'bottom':'20px'});
}
if (attributes == 'left') {
$(selector).animate({'right':'20px'});
}
if (attributes == 'down') {
$(selector).animate({'top':'20px'});
}
if (attributes == 'right') {
$(selector).animate({'left':'20px'});
}
}
else {
alert('Syntax Error!');
}
});