Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert code snippet to div

I used Jquery to insert a variable to div. Please check my code.

var msg = '<script src="https://gist.github.com/3010234.js?file=new.html.erb"></script>'
$('.result').html(msg);

msg variable contains a script that render a code snippet. msg is dynamic variable.

The above code is not working to insert code snippet to div.

Any Idea?

This script generate code snippet like this.

enter image description here

like image 632
Shamith c Avatar asked Oct 30 '25 09:10

Shamith c


2 Answers

To add script, I would add it to head like this;

var s = document.createElement('script');
s.src = 'https://gist.github.com/3010234.js?file=new.html.erb';
s.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(s);
like image 121
Blaster Avatar answered Oct 31 '25 22:10

Blaster


You cannot load a github gist into a page dynamically using that embed code. The embed code is fine if you can add the script tag to the HTML, but to do it dynamically via JavaScript as you are trying to do, it won't work because it relies on document.write().

Instead, use the github gists api:

$.get("https://api.github.com/gists/3010234", function(response) {
    $(".result").text(response.data.files["new.html.erb"].content);
}, "jsonp");

Working demo: http://jsfiddle.net/naTqe/

like image 22
gilly3 Avatar answered Oct 31 '25 22:10

gilly3