Aleksey Aleksey - 4 years ago 165
HTML Question

Javascript Button SRC

i need some help on JavaScript img src and click event.
Lets say i have a 2 images of button, pressed and unpressed.

btn1_On = new Image();
btn1_On.src = "../img/numpad/03_Button_1_Push.jpg";

btn1_Off = new Image();
btn1_Off.src = "../img/numpad/03_Button_1_No_Push.jpg";

and html:

<div class="Numpad_1" onmousedown="btnPress('btn1');return true;"
onmouseup="btnRelease('btn1');return true;"
onclick="btnPress('btn1');return true;">
<img src="..\img\numpad\03_Button_1_No_Push.jpg" id="btn1" />

i don`t want to multiply function for each button in html, so i create function to press btn and release:

function btnPress(btn) {
document.getElementById(btn).src = btn+'_On'.src;

function btnRelease(btn) {
document.getElementById(btn).src = btn + '_Off.src';

so, a problem is, btn+'_On'.src - cant init the path of image(undefined).
Thnx for any HELP.

P.S: I have some limitation , it must run on IE 6

Answer Source

If you have created object btn1_On in window/global context, then you use

document.getElementById(btn).src = window[btn+'_On'].src;

However, I would recommend to create a object, and then access the properties

var obj = {};
obj.btn1_On = new Image();
obj.btn1_Off = new Image();

Use Bracket notation to get properties based on string.

document.getElementById(btn).src = obj[btn+'_On'].src;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download