0
votes

I'm using Twitter Bootstrap's treeview plugin to generate a table of contents. The links I have for each node has the location of where the HTML is located and the anchor tag to go to. I parse this and load the HTML in a DIV on the current page and then scroll to the anchor tag. This works fine using the code below, but when I collapse or expand the nodes, it stops loading the HTML in the DIV and opens the page directly, basically ignoring the click event I have on the anchor tag. Any idea why that click event would not be triggered?

I have the following code to listen to buttons I have to expand or collapse the whole tree as follows:

    var $treeview = $('#treeview');
    $("#expand").click(function (e) {
        e.preventDefault();
        $treeview.treeview('expandAll', { silent: true });
    });

    $("#collapse").click(function (e) {
        e.preventDefault();
        $treeview.treeview('collapseAll', { silent: true });
    });

I set silent to true to suppress events but then my listener for anchor tags with hrefs in them will no longer get called. Everything works as expected otherwise so I'm unsure why these event calls cause this problem. And unfortunately, I can't use the nodeSelected event because subsequent clicks on the anchor tags cause the other HTML page to load, which is undesired; it needs to remain on the current page so the following code is the only way I was able to achieve that.

    $("a[href*='#']").click(function(e) {
        e.preventDefault();            
        if (this && this.href !== "") {
            // Split location and hash
            var hash = this.hash;
            var location = this.href.match(/[^#]*/g)[0];

            $('#contents').load(location, function () {
                $('html, body').animate({
                    scrollTop: $(hash).offset().top - 55
                }, 200);
            });
        }
        return false;
    });
1

1 Answers

1
votes

Maybe you can do like this

$("body").on("click", "#expand", function (e) {
    e.preventDefault();
    $treeview.treeview('expandAll', { silent: true });
});

$("body").on("click", "#collapse", function (e) {
    e.preventDefault();
    $treeview.treeview('collapseAll', { silent: true });
});

And

$("body").on("click", "a[href*='#']",function(e) {
        e.preventDefault();            
        if (this && this.href !== "") {
            // Split location and hash
            var hash = this.hash;
            var location = this.href.match(/[^#]*/g)[0];

            $('#contents').load(location, function () {
                $('html, body').animate({
                    scrollTop: $(hash).offset().top - 55
                }, 200);
            });
        }
        return false;
    });