Saturday, 15 June 2013

javascript - How do I make opening one dropdown close the other one? -



javascript - How do I make opening one dropdown close the other one? -

i'm trying larn pure native javascript, please, don't suggest using frameworks solve task. know the're awesome , learning them first thing i'm going when i'm done pure js :)

now, question. fiddle

as can see, have 2 custom dropdowns there. each of them can opened , controlled both mouse , keyboard. lastly thing need solve task implement next functionality: opening 1 dropdown should close other one, , clicking outside dropdown should close of opened dropdowns (assuming 1 can opened @ time).

i've tried adding onclick listener document, close dropdowns if of them open not used before, after i've clicked document once, dropdowns not showing more. that's not solution half of problem. since allocate flags bisopen objects, can't access them object see if it's triggered.

give me hint, please :)

move opening , closing logic own functions:

dropdown.prototype.open = function (e) { ... } dropdown.prototype.close = function (e) { ... }

and

this.htmldropdown.onclick = function (e) { if (this.bisopen) { this.open(e); } else { this.close(e); } }

(make sure open , close functions adjust bisopen, not onclick handler.)

then, add together list of current dropdowns exist:

function dropdown(htmlobject) { dropdown.dropdowns.push(this); ... } dropdown.dropdowns = []; // no 'prototype'

and finally, in open-er, close other dropdowns:

dropdown.prototype.open = function (e) { var dropdown; (var = 0; < dropdown.dropdowns.length; i++) { dropdown = dropdown.dropdowns[i]; if (dropdown !== this) { dropdown.close(); } } ... }

javascript onclick

No comments:

Post a Comment