I’m trying to teach myself a bit of javascript by writing a basic Web site (using Twitter Bootstrap) that presents a random quote from a Project Gutenberg novel, some discussion of it, and then further down the page has a link to go directly to the novel on Project Gutenberg.
I’ve used this JavaScript Source script to great effect… for the quote itself. But when it comes to linking the second element — the link to the quoted book — the text in the button doesn’t appear.
The HTML looks something like this:
<div class="childquote">
<p>
<span id="ran1">“Quote from a first novel.”<br>
- Bram Stoker, <em>Dracula</em></span>
<span id="ran2">“Quote from a second novel.”<br>
- Herman Melville, <em>Moby Dick</em></span>
and later down the page, the button HTML looks like this:
<div class="btn pull-right bookbutton">
<span id="ran1"><a href="http://www.gutenberg.org/ebooks/345">Read the book</a></span>
<span id="ran2"><a href="http://www.gutenberg.org/ebooks/2701">Read the book</a></span>
…obviously, all appropriate divs are closed, etc.
The CSS for the page sets display to “none” for all the random options on the page:
#ran1,#ran2,#ran3,#ran4,#ran5,#ran6,#ran7,#ran8,#ran9,#ran10,#ran11,#ran12,#ran13,#ran14,#ran15,#ran16,#ran17,#ran18 {
display:none;
}
And the JavaScript itself looks like this:
function messageLoad() {
var wch=Math.floor(Math.random()*18+1);
document.getElementById('ran'+wch).style.display='inline';
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
messageLoad();
});
As far as I understand it, because I don’t understand JavaScript at all, the JavaScript somehow “deactivates” the “display:none” CSS for a randomly selected “ranXX” so that the first part — the quote — will display as though “display:none” was not set for that random number.
But why doesn’t this same logic apply on down to the link? I get the random quote just fine, but the button text doesn’t appear at all.
The function is called
getElementById, so it will only ever return at most one element. In fact, IDs should be unique on a page – that’s the concept of IDs.You could give the link IDs an affix (say,
ran1link) so that they are uniquely identifiable, and have both elements set theirdisplaytoinline.Note that your
window.onloadtrick is not really necessary. There isaddEventListenerwhich can attach multiple functions to an event. That way you never have clashes with other code addingonloadfunctions.