views:

701

answers:

3

Possible Duplicate:
Multiline strings in Javascript

In Ruby you can do something like this

temp = <<-SQLCODE select * from users SQLCODE

This way you have very long string literals in your code without have to escape lots of characters. Is there something similar in JavaScript?

Currently I have javascript code like this, and its driving me nuts...

  new Element.update(lightbox_id, " \
    <div id='overlay' class='overlay' > \
    </div> \
    <div id='lightbox' class='lightbox'> \
      <div class='lightbox_title'> \
        <div class='corner_image' onclick=\"close_lightbox();return false;\"><a href='#' >" + corner_image + "</a></div> \
        <div class='lightboxname' id='lightboxname'>" + title + "</div> \
        <div class='close_image'> \
          <a href='#' onclick=\"close_lightbox();return false;\">Close</a> or Escape key\
        </div> \
      </div> \
      <div id='" + lightbox_content_id + "' class='lightbox_content'>    \
      </div> \
      <script>  \
        watch_for_escape(); \
      </script> \
    </div> \
");
+3  A: 

The syntax you are referring to is often known as here-document (or HEREDOC) and no, it is not available in Javascript.

Adding a backslash as you have been doing is the appropriate way to span strings over multiple lines in JavaScript.

thomasrutter
+1  A: 

Having html inline like that is bad practice, but if you really want to handle it cleaner, try this:

Place a hidden div on your page with the html you want, and replace the custom params with something like {title}. When calling update, pass yourdiv.innerHTML.replace(...

Luke Schafer
A: 

If you're using Rails, then it becomes a lot cleaner with rjs to update a div with some multiline HTML:

page.replace__html 'lightbox_id', :partial => 'overlay'

then overlay.html.erb would contain the raw html above without escaping.

The added benefit is that the fragment 'overlay' could also be used in the initial page load as well, which in a lot of cases is what you want.

Julian