Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Javascript help

Name: Anonymous 2012-08-03 12:52

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/

Name: Anonymous 2012-08-03 12:54

>>1
By the way, the feature is opt-in, so you need to enable Post Expansion in the Board Options menu.

Name: Anonymous 2012-08-03 13:03

Got this answer on stackoverflow. Any comments on it?
>The document.getElementsByClassName method returns a live node list. Therefore, the links will change, and potentially have not item at position e any more when the handler is fired - resulting in an undefined value that throws an error when accessing its firstElementChild property.

>You should not need to get the current element from the links list. Get it dynamically via a.target or just this:


function postExpansionPrep() {
    if (document.body.className)
        return;
    var links = document.getElementsByClassName("abbrev");
    for (var i = 0; i < links.length; i++ ) {
        var child = links[i].firstElementChild;
        if (!child) // could be null as well
            continue;
        child.addEventListener("click", function(e) {
            expandPost(this);
            e.preventDefault();
        }, true);
        console.log(child.href);
    }
}

Don't change these.
Name: Email:
Entire Thread Thread List