[thelist] [JavaScript] way around these global vars?

Tom Dell'Aringa pixelmech at yahoo.com
Tue Feb 7 09:47:56 CST 2006

Hi folks,

Still working on my kiosk project and I'm wanting to make hit states for my buttons. The buttons
look like this:

<input type="submit" name="viewall" style="border: 0; background: #fff; background-image:
url(/images/btn-viewall.gif); width: 300px; height: 75px;" value="" onclick="showHit(this);">

Yeah, it's ugly and the local style blows, but that's the way it has to be for right now. In any
event, I've written this little showHit() function attached to the onclick to give the user a
little feedback that yeah, you did hit the button and it did register. It sends itself as the only
argument. See below:
var lastImg;
var currentBtn;
function showHit(btn)
        currentBtn.style.backgroundImage = "url(/images/" +lastImg+ ".gif)";
        var urlArray = btn.style.backgroundImage.split("/");
        var img = urlArray[urlArray.length -1].replace(".gif)", "");
        var on = "url(/images/" + img + "_on" + ".gif)";
        lastImg = img;
        currentBtn = btn;
        btn.style.backgroundImage = on;
        setTimeout("showHit()", 500)
So it tears the background string apart, grabs the image name, adds '_on' for the onstate, then
calls itself a half second later and puts the old image back. It works fine, but I don't like the
global vars and I'm wondering how I can get around using them. 

When I tried to send the button object/img name via setTimeout() recursively, they are out of
scope, so that does not work. 

Any ideas? Feel like I might be missing something obvious.




Professor Rumford: 'But I still don't understand about hyperspace.' 
The Doctor: 'Well, who does?' 
K9: 'I do.' 
Doctor: 'Shut up, K9!' 

More information about the thelist mailing list