Search code examples
htmlcssbootstrap-4scrollspy

How can I display the current section name in a top dropdown nav using scrollspy?


I want to display the section's name on the dropdown tab using bootstrap scrollspy. When I scroll now, I only see section (which I would exclude) and I would like to see the current section in the dropdown bar as in when its not opened. So when I touch section 2 while scrolling I would like to see section 2 in the dropdown bar on top. At first, of course, I would like the bar to display section 1.

This is my code: https://codepen.io/alyssaalex/pen/rNNGrLy

I would appreciate it if someone could provide some help in this regard. Thanks!


Solution

  • You need to trigger an event on section change. And then get the section name and put on the dropdown title.

    add this code in your JS

    $(".navbar").on("activate.bs.scrollspy", function(){
      $("#section_ddl").html('');
      var sections = new Array("Section 1", "Section 2");
      var x = $(".nav li.active > a").text();
      if(sections.indexOf(x) != -1){
        $("#section_ddl").html(x + '<span class="caret"></span>');
      }
      else {
        $("#section_ddl").html('Section <span class="caret"></span>');
      }
    });
    

    If you add/remove sections, you only need to put section names in the sections array.

    Note: section_ddl is the id of the dropdown.

    You can see the working example here