Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open and scroll to tab from url hash (JS/Jquery/Bootstrap)

So I have a comment system with one deep nesting. I'm using bootstraps javascript file, but only the collapse and animate css styling. So I don't use nav-tab and such

A button exists on all comments that have a reply. The number 1 refers to the ID of the parent (replies of comment with the id of 1).

<a class="btn" type="button" data-toggle="collapse" href="#replies_1">X replies</a>

Then I have a div, that is the container for all children of the parent comment

<div class="collapse" id="replies_1">

When I click on the anchor, as you would guess, this div gets appended the class in and transitions nicely to open and show the comments children.

I have tried one thing that worked, except for the scrolling part

$(document).ready(function(){
    if(window.location.hash != "") {
        $('a[href="' + window.location.hash + '"]').click();
    }
});

This opens up the correct tab, which is great. However, since the tab has the class collapse which has the css rule display:none; and adds the inline rule display: none;

Now, my script doesn't manage to scroll to the correct location, because the collapsed element has those rules.

Though, I don't really need to scroll to the replies, but the parent.

So what I really need is to scroll to another anchor id that has the same suffix ID, but a different prefix, but still open the replies tab as I do with the code above

Since the children are inside a tab with an id of replies_{id}, I could scroll to the parent which is a ul item with the id of comment_{id}

The ul looks like this: <ul class="comment__item" id="comment_{id}">

like image 724
Pistachio Avatar asked Nov 08 '22 10:11

Pistachio


1 Answers

Try this way,

 $(document).ready(function(){
    if(window.location.hash != "") {
        var end_id = window.location.hash.split('__')[1];
        $("html,body").animate({scrollTop: $("[id$='__"+ end_id +"'").offset().top},"slow");
    }

});
like image 159
Ahad Avatar answered Nov 14 '22 22:11

Ahad