'JavaScript changing on click
I'd 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 existing 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>
Solution 1:[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
Solution 2:[2]
Don't set the event handlers that way. Use addEventListener and (for IE) attachEvent.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Luke Schafer |
Solution 2 | Robusto |