Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
    
according to stackoverflow.com/questions/1071386/… this does work. Can someone confirm? –  Nick Ginanto Nov 9 '11 at 18:32

3 Answers 3

up vote 2 down vote accepted

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.

share|improve this answer

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); 
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.