0

Id like some help changing this javascript onclick event to just load the data on page the page load... Preferably not using the body on load tag...

So obviously I'd pre set the var for term inside the script term rather than the excisting on click event..

Hope that made sense

<p><a id="keywordlink" href="?term=wombats">Get keywords for wombats</a></p>
<script type="text/javascript" src="keywords.js"></script>
<script type="text/javascript">
  var x = document.getElementById('keywordlink');
  if(x){
    x.onclick = function(){
      var term = this.href.split('=')[1];
      this.innerHTML += ' (loading...)';
      KEYWORDS.get(term,seed);
      return false;
    }
  }
  function seed(o){
    var div = document.createElement('div');
    var head = document.createElement('h2');
    head.innerHTML = 'Keywords for '+o.term;
    div.appendChild(head);
    var p = document.createElement('p');
    p.innerHTML = o.toplist;
    div.appendChild(p);
    var head = document.createElement('h3');
    head.innerHTML = 'Details:';
    div.appendChild(head);
    var list = document.createElement('ol');
    for(var i=0,j=o.keywords.length;i<j;i++){
      var li = document.createElement('li');
      li.innerHTML = o.keywords[i].term + '('+o.keywords[i].amount+')';
      list.appendChild(li);
    }
    div.appendChild(list);
    x.parentNode.replaceChild(div,x);
  }
</script>
Webby
  • 2,385
  • 5
  • 23
  • 32
  • If i understand correctly, you're asking how to move this onclick event to execute when the page is loaded. If so, just use the document.ready() event in jQuery. Or if you dont want to use jQuery - here's a thread explaining how to do it in js: http://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery – RPM1984 Jun 06 '10 at 23:29

2 Answers2

1

change this:

if(x){
    x.onclick = function(){
      var term = this.href.split('=')[1];
      this.innerHTML += ' (loading...)';
      KEYWORDS.get(term,seed);
      return false;
    }
  }

to something like this:

function loadSomething(){
  var term = x.href.split('=')[1];
  x.innerHTML += ' (loading...)';
  KEYWORDS.get(term,seed);
  return false;
}
loadSomething();

you can leave it where it is, but for readability, put it below the seed function.

You should use something like onload or document.ready, but alternatively you can move the whole script file to the bottom of the page

Luke Schafer
  • 8,977
  • 2
  • 26
  • 28
0

Don't set the event handlers that way. Use addEventListener and (for IE) attachEvent.

Robusto
  • 29,248
  • 8
  • 52
  • 76