Question

I wrote one script which gets an image url through JSONP, and then I needed to write that to browser, this is a status image which is onling.png, offline.png and so on

my script looks like this.

<div id='STATUSDIV'></div>
    <script language=javacsript type=text/javascript src=http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js></script>
    <script type="text/javascript">$(document).ready(function()
    { 
        $.getJSON('http://MYSSERVERNAME.COM/get.php?callback=?','q=value&index'+Math.random(),
        function(res)
        { 
            document.getElementById('STATUSDIV').innerHTML = ("<img src='"+res.img+"' />");
        });
    });
    </script>

using this code, I am able to get an image inside div statusdiv, however I can not use same code block twice on single page as both will point to same div.

quick thing I can do is that I can ask end user who will copy this code multiple time on each page to change div id so that that image will load on differnt div.

But I wanted to have same code wherever copied just writes image inline. kind of createelement and write in that element. but thats not working. document.write does not work either as it replaces everything.

Is there a way that when this code block called, Instead of writing innerhtml, code creates a dynamic div right there on the page and writes image in that. and this image writing and creating div happens where script block is called. so that If same script is called in header and footer, status image will appear on both header and footer.

Was it helpful?

Solution

The cleanest way I know of is to create a function for your code that should get included very early in the page so it's available everywhere:

function insertStatusHere() {
    var thisId = "status" + insertStatusHere.myDivCntr++;
    document.write('<div class="statusContainer" id="' + thisId + '"></div>');
    $(document).ready(function() {
        $.getJSON('http://MYSSERVERNAME.COM/get.php?callback=?','q=value&index'+Math.random(), function(res) { 
            document.getElementById(thisId).innerHTML = ("<img src='"+res.img+"' />");
        });
    });
}
insertStatusHere.myDivCntr = 0;

Then, any place in the page where someone wants a status image, they can put this inline script:

<script type="text/javascript">
insertStatusHere();
</script>

This dynamically inserts a div with a unique div ID at the place that the function call is made and it keeps track of each ID that is used in the closure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top