-1

Because I think using multi-line strings in a var is not very convenient. What are some other ways to handle this? I don't want my code to be like this:

var str = "<p>\'Hello World\'</p>"+"<a href=\'www.blah.com\'>click me</a>";

And so on...

I need this because I want the HTML to load after a javascript event. I don't want to use escape characters for quotes as it will make the code a bit unreadable specially when you want to make changes to it.

Update:

I don't want the code to load at the same time as the page loads. Setting it to display: none; then display: block; will slow things down.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Angel Angeles III
  • 300
  • 1
  • 4
  • 14

3 Answers3

1

My first instinct was a hidden element but I saw the comment about not wanting the html to load.
My next thought was to try the XML <!CDATA[...]]> block wihtin the hidden element but testing showed that won't work in HTML.

This has an incredibly hacky feel but it could work (at least it did in my very limited testing).

<script id="str">/*
    <p>'Hello World'</p>
    <a href='www.blah.com'>click me</a>
 */</script>

The use jquery to extract the html and strip out the comments.

  var str = $("#str").html();
  str = str.slice(2, str.length-3).trim();
drs9222
  • 4,448
  • 3
  • 33
  • 41
0

Say you have have

<p id="message"> Hello World</p>

On your CSS, you would have:

#message
{
  display:none;
  /* other css*/
  }

On your JavaScript you could have something like:

/* after some event or something */
document.getElementById("message").style.display = "block";

What do you think?

Erick
  • 823
  • 16
  • 37
0

Thanks to @drs9222 I have finally found a way to do this. I will answer my own question for so that future readers will know what I have done to solve my problem. Also thanks to @dandavis for giving my an idea on using script type="text/plain". This is my answer.

<!DOCTYPE html>
<html>

<head>
  <title>Testing</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>

<body>

  <script type="text/plain" id="preCode">
    <h1>Hello World</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sit cumque nobis quo et ducimus. Porro, minima, facilis. Explicabo iure non optio quae! Eveniet dolore ex sunt nemo maiores eum voluptatum.</p>
  </script>

  <div class="insideHere">
    <!-- preCode will go inside here -->
  </div>

  <input id="clickMe" type="button" value="Click Me!" />

  <script>
    $('#clickMe').click(function() {
      $('.insideHere').append($('#preCode').html());
    });
  </script>
</body>

</html>

This code will not get in the way of loading other elements except for the code itself.

Angel Angeles III
  • 300
  • 1
  • 4
  • 14