Forum Moderators: open

Message Too Old, No Replies

iterate?

         

webaster

6:35 pm on Jul 14, 2005 (gmt 0)

10+ Year Member



idea is to find for each named div the sole and only img and assign onmouseover, onmouseout, ... it does not work - is the iteration ok?

HTML

<body id="homepage">
<div id="oneNav"><a><img src="nav1_navi.gif"></a></div>
<div id="twoNav"><a><img src="nav2_navi.gif"></a></div>
<div id="threeNav"><a><img src="nav3_navi.gif" ></a></div>
<div id="fourNav"><a><img src="nav4_navi.gif" ></a></div>


JAVASCRIPT

ids=['oneNav','twoNav','threeNav','fourNav'];

for(var i=0;i<ids.length;i++){ // iterate image of each div as defined
in latter array of named divs

navIds[i] = document.getElementById(ids[i]);
imgs = navIds[i].getElementsByTagName('img'); // define variable that
collects the sole img of each named divs
imgs[0].onmouseover = mouseGoesOver;
imgs[0].onmouseout = mouseGoesOut;
imgs[0].onclick = mouseGoesClick;
....
}

ORBiTrus

6:45 pm on Jul 14, 2005 (gmt 0)

10+ Year Member



JavaScript should read as:

function init () {
var ids=['oneNav','twoNav','threeNav','fourNav'];

for(var i=0;i<ids.length;i++) {
var navId = document.getElementById(ids[i]);
var imgs = navId.getElementsByTagName('img');
imgs[0].onmouseover = mouseGoesOver;
}
}

Don't forget to var anything with local scope, else it will get global scope!

Your problem was saying navIds[i] = ....
since navIds was not defined, and did not need to be.

Also, you need to have the Javascript execute AFTER the elements have loaded. That's why I use body.onload() all the time.

Lastly, it is preferable to add an event listener rather than override the onmouseover.

webaster

11:08 pm on Jul 14, 2005 (gmt 0)

10+ Year Member



I found that img[0], and all in one for loop, etc... same result here.
[/CODE]
ids=['oneNav','twoNav','threeNav','fourNav'];

for(var i=0;i<ids.length;i++){
var navIds = document.getElementById(ids[i]);
var imgs = navIds.getElementsByTagName('img');
imgs[0].onmouseover = mouseGoesOver;
[/CODE]