0

This code will run (at least in Firefox ) and will create and attach the onmouseover event handler on the three elements designated to have a submenu by having the name preceded by an _. It does not add the handler to those which should not have it.

If I trace through in Firebug, everything appears to be working fine; that is the handler is attached with the correct id and navtitle.

In the browser, the correct elements have a mouseover event which fires. HOWEVER, the parameters passed to that event handler in EVERY case are '6' and 'Other' despite the fact that no event handler is even attached to 'Other'. I think I've scoped everything correctly so I do not understand why this is happening.

What am I missing here?

Thanks!

// Parent element to which I will add child elements

var navdiv = document.getElementById('nav') 

var navarray = ['','Home', '_Books', '_Pictures', '_Characters','Other']

// Horizontal Menu

var nnav = navarray.length

for (var ii = 1; ii < nnav; ii++) 
{

// get title and determine whether it has a submenu
var subflag = false
var navtitle = navarray[ii]
var firstchar = navtitle[0]
if (firstchar == '_') 
{
    navtitle = navtitle.substring(1, navtitle.length - 1)
    navtitle += '*'
    subflag = true

}


// Create Div

var naventry = document.createElement('div')
var navid = 'nav' + navarray[ii]
naventry.setAttribute('id', navid)
naventry.setAttribute('class', 'navitem')
// Create Link
var lnk = document.createElement('a')
lnk.setAttribute('href', navarray[ii] + '.html')
if (subflag) // will have a submenu
{
    lnk.onmouseover = function () { dropmenu(ii, navtitle) }
}

var txtnode = document.createTextNode(navtitle)
lnk.appendChild(txtnode)

naventry.appendChild(lnk)
navdiv.appendChild(naventry)
lnk = null
}

function dropmenu(which, ntitle) 
{
alert('In drop menu: Id = ' + which + '  ' + ntitle)
return false;
}
Mona Everett
  • 49
  • 1
  • 2
  • 10

3 Answers3

0

dropmenu(ii, navtitle) is the cause because ii is equal to nnav when the loop terminates. you need to take a snapshot of ii and pass that to dropmenu instead.

akonsu
  • 28,824
  • 33
  • 119
  • 194
0

Change this,

if (subflag) // will have a submenu
{
    lnk.onmouseover = function () { dropmenu(ii, navtitle) }
}

to this

if (subflag) // will have a submenu
{
    (function(i){
        lnk.onmouseover = function () { dropmenu(i, navtitle) }
    })(ii);
}

I hope it'll solve the problem.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

Try assigning your mouseover handler like this:

lnk.onmouseover = function () {
    return function () {
        dropmenu(ii, navtitle);
    }
};

This makes the handler a closure which will retain the values of ii and navtitle at the time the handler was created.

Community
  • 1
  • 1
pete
  • 24,141
  • 4
  • 37
  • 51