Basically, what I wanted was to be able to say: "This group of options under this tag are a logical set, and only one of them may be considered active at any given point in time"
This is what I converged upon:
function UniqueSelection(id, extras, allowToggle, childTag) {
if(!childTag)
childTag = 'li';
var parent = document.getElementById(id);
var items = parent.getElementsByTagName(childTag);
var currentItem = false;
function choose(choice) {
if(!currentItem) {
currentItem = items[choice];
currentItem.className = 'active';
}else{
if(currentItem != items[choice]) {
currentItem.className = 'inactive';
currentItem = items[choice];
}
if(allowToggle && currentItem.className == 'active') {
currentItem.className = 'inactive';
}else {
currentItem.className = 'active';
}
}
}
for(var i = 0; i < items.length; i++) {
items[i].onclick = (function(id, func) {
if (!func) {
func = function() {
return true;
};
}
return function() {
choose(id);
func();
};
})(items[i].id,
(extras ? extras[items[i].id] : false));
if(items[i].className == 'active') {
currentItem = items[i];
}
}
}
This version does exactly what I need it to, although the creation syntax is a little funky if you're not used to passing objects as parameters:
//to create just a list, no extra actions
justAList = new UniqueSelection('simple-list');
//to create a list where three elements have extra actions:
normalUse = new UniqueSelection('normal-list',
{ 'first-element': firstElementsFunc,
'second-element': secondElementsFunc,
'third-element' : thirdElementsFunc});
This version also doesn't loop through the child elements on every click - it just works with the current element, which means that the choice function shouldn't slow down on large lists.
I'm not sure if this is the javascripty way of accomplishing this, but it works for me. It's not exactly efficient as far as memory usage goes, but it could be a lot worse (and it works). I'm still learning javascript, and it hasn't quite seeped entirely into my brain yet, but it's getting closer.
Nice blоg here! Also your site lοаdѕ up ѵery fast!
ReplyDeleteWhat host are you using? Can I get yοur affilіate link to your host?
I wish mу website loаded uρ аѕ quickly as yours lol
Feel free to ѵisit my blog ... weight loss
ӏt's remarkable in favor of me to have a web site, which is good designed for my know-how. thanks admin
ReplyDeleteMy weblog quick payday loans