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

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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); 

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.