0

I want to make a jQuery based custom popup window for my site using javascript.

I prototyped it by storing the HTML to go in the popup inside a javascript string variable and then display that string thus:

$('#pop_div').html(string);

where string is defined thus:

var string= '<div class="className">' +
    'HTML Content'+
'</div>'

I've seen a few websites that do this but think it is incorrect.

It works for static html snippets but not for rails generated html using <%= .. %>

What is the best way of loading HTML code generated by rails into a javascript/jquery script?

thanks

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244
  • according to http://stackoverflow.com/questions/1071386/jquery-html-and-new-line-characters this does work. Can someone confirm? – Nick Ginanto Nov 09 '11 at 18:32

3 Answers3

2

It is fine to do

<script>var string = <%= escape_javascript(...) =>;</script>

since the escape_javascript does the work of ensuring that the original string will be interpreted properly by the JavaScript interpreter.

See Why escape_javascript before rendering a partial? for more discussion.

Note, that if you want to put this in an onclick handler instead of inside a <script> element you may need to escape_javascript and then HTML escape the result.

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
0

It would be easier to store the element in a variable:

var el = $("<div class='className' />").html("HTML Content");

//append the element to the div
$("#pop_div").append(el); 
James Johnson
  • 45,496
  • 8
  • 73
  • 110
0

How about in 3 steps:

var htmlContent = 'HTML Content';

var elem = $('<div />').addClass("className").html(htmlContent);

$('#pop_div').empty().append(elem);

Now, I've only done "hello world" with RoR, but use Mike Samuel's escape_javascript code and that might address your needs.

artlung
  • 33,305
  • 16
  • 69
  • 121