tags:

views:

417

answers:

4

I want to create a javascript badge that displays a list of links. We host the javascript on our domain. Other sites can put an empty div tag on their page and at the bottom a reference to our javascript that would render the content in the div tag. How do you implement something like this?

+1  A: 

just as you say, have them put a div at the bottom of their page:

<div id="mywidget"></div>

then have them link to your javascript:

<script type="text/javascript" src="http://yourdomain.com/mywidget.js"&gt;&lt;/script&gt;

then have them alter their body tag, or onload to call your script

<script type="text/javascript">
  document.body.onload = loadYourWidget();
</script>
Owen
Can you expand on what loadYourWidget() looks like. How do you reference the div?
philcruz
you can use "document.getElementById('mywidget')" to grab the div mentioned in my answer, and just populate it as mentioned with whatever links you wanted.
Owen
A: 

Like @Owen said, except why not craft your javascript so that

<script type="text/javascript" src="http://yourdomain.com/mywidget.js"&gt;&lt;/script&gt;

does the work of populating <div id="mywidget"></div> on its own, thus negating the need for them to call loadYourWidget() from their DOM load if you include the script tag right after the mywidget div in the html source. This isn't really a best practice, but I think it'll work.

Example for your mywidget.js code:

document.getElementById('mywidget').innerHTML = "<a href=''>LinkOne</a> <a href=''>LinkTwo</a>";
Gabe Hollombe
+4  A: 

I would give the SCRIPT tag an ID and replace the script tag itself with the DIV + contents, making it so they only have to include one line of code. Something along the lines of the following:

<script id="my-script" src="http://example.com/my-script.js"&gt;&lt;/script&gt;

In your script, you can swap out the SCRIPT tag for your DIV in one fell swoop, like so:

var scriptTag, myDiv;
scriptTag = document.getElementById('my-script');
myDiv = document.createElement('DIV');
myDiv.innerHTML = '<p>Wow, cool!</p>';
scriptTag.parentNode.replaceChild(myDiv, scriptTag);
Andrew Hedges
+1  A: 

You do not necessary need an initial div to fill with you link list.

Simply create the div using document.write at the place where the script is placed.

<script type="text/javascript" src="http://domain.com/badge.js"&gt;&lt;/script&gt;

... and in your script:

var links = [
  '<a href="#">One</a>',
  '<a href="#">Two</a>', 
  '<a href="#">Three</a>'
];

document.write("<div>" + links.join(", ") + "</div>");

Another benefit is that you do not have to wait for the page to be fully loaded.

aemkei