1

I want to store javascript code in a javascript variable. To explain clearly, please consider example:

<html>
<body>

<script type="text/javascript">
<!--

    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>

<a onclick="toggle_visibility('1');toggle_visibility('2');">Click here to toggle visibility of element </a>
<div id="1">This is 1</div>
<div id="2">This is 2</div>

<script type="text/javascript">
//document.getElementById('2').style.display='none';
</script>

</body>
</html>

Now suppose all this code is in a variable as a string or something. (i want to do this because i am exporting file to another html page where the code should get copied.) I used all variables such as using \ before ' and so on. referring to http://www.w3schools.com/js/js_special_characters.asp

2
  • Hi @shashank please edit your code, by clicking on the edit button and select the section that has the code and click on the {} button Commented May 28, 2011 at 6:10
  • 1
    Your example seems to be missing... the example part. I can't tell what you're asking. But putting code in a string is usually a bad approach; can you use a function in an external js file instead? (btw, w3schools is a terrible resource; try developer.mozilla.org.) Commented May 28, 2011 at 6:10

3 Answers 3

2

Store like this: var myFunc = function(){ do stuff }

Run like this: myFunc();

Sign up to request clarification or add additional context in comments.

Comments

0

To interpret JS code you need to use the JS function eval()

 var code = "alert('Ok')";

 eval(code);

Here is why using eval() is a bad idea:

Why is using the JavaScript eval function a bad idea?

Comments

0

Maybe try something like this:

var quoteElement = document.getElementById('2');
var quote = quoteElement.value;

// or even ..
var quote = document.getElementById('2').value;

You would now have the text value of your element in a variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.