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

ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
shashank
  • 19
  • 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 – Ibu May 28 '11 at 06: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.) – Eevee May 28 '11 at 06:10

3 Answers3

2

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

Run like this: myFunc();

ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
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?

Community
  • 1
  • 1
Pablo
  • 5,897
  • 7
  • 34
  • 51
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.

Stephane Gosselin
  • 9,030
  • 5
  • 42
  • 65