Can any of you guys help me out with a Javascript problem? I’m trying to write a post expansion feature for my site, and for some reason whenever I expand the first post, the second will no longer expand, and will instead redirect to the full post on the thread page. If I expand the second post and then the first next, I don’t have the problem.
Here’s the code that runs when the page is loaded:
function postExpansionPrep(){
if(!document.body.className){
var links = document.getElementsByClassName("abbrev");
for (var i = 0; i < links.length; i++ ){
(function(e) {
links[e].firstElementChild.addEventListener("click", function(a){ expandPost(links[e].firstElementChild); a.preventDefault(); }, true);
console.log(links[e].firstElementChild.href);
})(i);
}
}
}
And here’s the code that runs when you click on the link to expand a post.
function expandPost(link){
if(link.hash){
$.get(link, function(data) {
var loadedPost = $(data).find("#reply" + link.hash.replace("#",""));
document.getElementById("reply" + link.hash.replace("#","")).lastElementChild.innerHTML = $(loadedPost).find("blockquote").last().html();
});
}
else{
$.get(link, function(data) {
var loadedPost = $(data).find("#parent" + link.pathname.substring(link.pathname.lastIndexOf("/")+1));
document.getElementById("parent" + link.pathname.substring(link.pathname.lastIndexOf("/")+1)).lastElementChild.innerHTML = $(loadedPost).find("blockquote").last().html();
});
}
}
You can see the issue in action here: http://www.glauchan.org/test/
By the way, the feature is opt-in, so you need to enable Post Expansion in the Board Options menu.
The
document.getElementsByClassNamemethod returns a live node list. Therefore, thelinkswill change, and potentially have not item at positioneany more when the handler is fired – resulting in anundefinedvalue that throws an error when accessing itsfirstElementChildproperty.You should not need to get the current element from the
linkslist. Get it dynamically viaa.targetor justthis:Btw, as you have jQuery available you should use it, especially for the event handler attaching: