Forum Moderators: open
<html>
<style type=text/css>ul {display:none}</style>
<div id=blogmenu>
<p><a href=category1.html>Category 1</a>
<ul id=category1.html>
<li>Details 1
</ul>
<p><a href=category2.html>Category 2</a>
<ul id=category2.html>
<li>Details 2
</ul>
</div>
<script type=text/javascript>
linkies=document.getElementById("blogmenu").getElementsByTagName("a");
for(var i=0,l=linkies.length;i<l;i++) {
linky=linkies[i];
detailsID = linky.href;
detailsID = detailsID.replace(/.*\//,"");
linky.onclick = function() {
document.getElementById(detailsID).style.display="block";
return false;
}
}
</script>
</html>
[edited by: MichaelBluejay at 2:39 am (utc) on April 17, 2009]
var linkies = document.getElementById("blogmenu").getElementsByTagName("a");
for(var i=0,l=linkies.length;i<l;i++) {
linkies[i].onclick = function() {
var detailsID = this.href; // this = linky
detailsID = detailsID.replace(/.*\//,"");
document.getElementById(detailsID).style.display="block";
return false;
}
}
var i, l, linky, detailsId, linkies = document.getElementById("blogmenu").getElementsByTagName("a");
for (i = 0, l = linkies.length; i < l; i++) {
linky = linkies[i];
detailsID = linky.href;
detailsID = detailsID.replace(/.*\//,"");
linky.onclick = (function(d) {
return function() {
document.getElementById(d).style.display = "block";
return false;
};
})(detailsID);
}
Either method should work. daveVK's method will get the href and perform the replace each time the link is clicked, and the closure approach will do it only once when you assign the event handler. One method might yield slightly better performance than another depending on how many links you are doing this for, but both should get the job done.
[edited by: Fotiman at 1:37 pm (utc) on April 17, 2009]
function show() {
var detailsID = this.href.replace(/.*\//,"");
document.getElementById(detailsID).style.display="block";
return false;
}
If using closures you should reset the onclick to null on page unload to avoid memory leakage.