Reputation: 19358
I want to store javascript code in an object, and then run parts of it when the user clicks a button. So far I have this:
var exampleCode = {
test: "$('body').css('background: pink');"
}
$(document).ready(function(){
console.log(exampleCode.test);
exampleCode.test;
});
I have two questions, the first is, how to I get the code to actually run?
The second is, what do I do if I want to have some html in my javascript, say like the following line of code:
$('body').append('<div class="whatever"></div>');
This wont play well with the double quotes around the object value.
My goal with all of this is to be able to both run and display code as text on the same page without having the code written twice, so if you have other suggestions, that would be great.
Upvotes: 0
Views: 82
Reputation: 33870
You can't acually do a "string of code", so the only way to run you code is to do this :
var exampleCode = {
test: function(){$('body').css('background', 'pink');}
}
$(document).ready(function(){
console.log(exampleCode.test); //No "()" for the function
exampleCode.test();
});
You save a function in the object and the you call it.
If you want to append the text of the function, you can do this :
$('body').append(String(exampleCode.test))
This will append the function, however there is no formating
However, you can use the javascript function .replace()
to do a little bit of formating.
//Really weak example, can be optimised
var txtCode = String(exampleCode.test)
txtCode = txtCode.replace(';', ';<br/>')
txtCode = txtCode.replace('{', '{<br/>')
txtCode = txtCode.replace('}', '}<br/>')
var code = $('<code/>').html(txtCode)
$('body').append(code)
Additional information: You can escape character with "\".
Doing alert('How\'s it?')
will pop the alert "How's it?" and alert("See that : \"!")
will pop the alert "See that : "!".
Upvotes: 6