Mootools - Loading external script as HTML
by rome_margo
HTML
<div id="cat_table">
<div id="catClick1">1</div>
<div id="catClick2">2</div>
<div id="catClick3">3</div>
<div id="catClick4">4</div>
<div id="catClick5">5</div>
</div>
<div id="rt-main">
</div>
<div class="itemBox" id="item1">a</div>
<div class="itemBox" id="item2">b</div>
<div class="itemBox" id="item3">c</div>
<div class="itemBox" id="item4">d</div>
<div id="scriptPlaceHolder"></div>
CSS
#rt-main{
border: solid 1px red;
width:100px;
height: 100px;
}
JavaScript
window.addEvent('domready', function(){
function ajaxfunc(i)
{
return function(e){
e.stop();
var requestData = new Request({
url: '/echo/html/',
data: {
html: "<script src='//cdnjs.cloudflare.com/ajax/libs/mootools-more/1.4.0.1/mootools-more-yui-compressed.js'>gotoItem = function(){ alert('gotoItem called')}<\/script>",
delay: 1
},
method: 'post',
evalScripts: true,
evalResponse: true,
onComplete: function (response) {
//Put the response into a placeholder
document.getElementById('scriptPlaceHolder').innerHTML = response;
//Get a reference to to DOM version of the script
var scriptPlaceHolder = $('scriptPlaceHolder').getChildren('script')[0];
//Get the body of the response from the placeholder
var scriptBody = scriptPlaceHolder.innerHTML;
//Get the src attribute from it
var scriptSrc = scriptPlaceHolder.getAttribute('src');
//Create a new script element
var newScript = document.createElement('script');
//Add it to the destination div
document.getElementById('rt-main').appendChild(newScript);
//Add the scriptBody to the new script tag (this has to happen AFTER it's appended)
newScript.innerHTML = scriptBody;
//Add the scriptSrc to the new script tag (this has to happen AFTER it's appended)
newScript.setAttribute('src', scriptSrc);
//Test that the function works
...