big_smile
big_smile

Reputation: 1523

Java script - Keep buttons hidden until page load

I have built a horizontal scrolling website. I don't really know much about Java Script, but I downloaded this script called Horizontal Tiny Scroller that lets you scroll the website horizontally, without using the scroll bar.

Everything works perfectly except the script only loads once everything else on the page has finished loading. As my site has a high number of graphics, this creates a usability as the scroller buttons do not immediately work. I'm guessing most the users will assume that the buttons are broken.

After a bit of research I have found that there is no solution to making the buttons load before the graphic, so I will just have to hide the buttons until the page has loaded.

The Tiny Scroller script uses a document.writeln command to make the buttons appear on the page:

document.writeln('<a href="javascript://" id="left-arrow"></a>\n<a href="javascript://" id="right-arrow"></a>');

Using online tutorials, I created two CSS classes: .visible {display:block;} & .hidden {display:none;}. I rewrote the document.writeln command so the buttons were assigned the .hidden class by default:

document.writeln('<a href="javascript://" id="left-arrow" class="hidden"></a>\n<a href="javascript://" id="right-arrow" class="hidden"></a>');

Finally, I wrote an onload=function to swap the .hidden class with the .visible class:

onload=function() {
     document.getElementById('left-arrow').className='visible';
     document.getElementById('right-arrow').className='visible';
}

The finished script can be seen here

Everything works fine, and the buttons only appear when the page has loaded. HOWEVER, the scrolling function doesn't work any more! If I delete the onload=function everything works again (but then of course the buttons appear before the page has finished loading).

Does anyone have any pointers as to what I'm doing wrong?

Upvotes: 0

Views: 738

Answers (2)

mwilcox
mwilcox

Reputation: 4132

I recommend you connect to the onload instead of overwriting it.

if(window.attachEvent){ //IE
    window.attachEvent("onload", myChangeVisFunc);
}else{
    window.addEventListener("load", myChangeVisFunc, false);
}

Upvotes: 1

bluesmoon
bluesmoon

Reputation: 4320

You're probably overwriting the onload handler that the library sets. This is probably not the best way to accomplish what you need to do, but given that you're new to Javascript, we'll try and make it work.

Change your onload handler to this:

function handler() {
    document.getElementById('left-arrow').className='visible';
    document.getElementById('right-arrow').className='visible';
}

var old_onload = window.onload;
window.onload = function() {
    handler();
    if(old_onload) {
        old_onload();
    }
};

This will check if an onload handler has already been set, and will not overwrite it if it has.

Upvotes: 1

Related Questions