How to create links to sections within your webpage using Framework7

64 views Asked by At

I am familiar with the classic method of linking to sections on your webpage, whereby the anchor tag is made to point to some elements id within the page, like this sample

<div class="main" id="section1">
  <h2>Section 1</h2>
  <p>Click on the link to jump to section 2.</p>
  <a href="#section2">Click Me</a>
</div>

<div class="main" id="section2">
  <h2>Section 2</h2>
  <p>Click on the link to jump to section 1.</p>
  <a href="#section1">Click Me</a>
</div>

But when I tried this trick within a Framework7 app, it didn't work. I guess it has to do with how Framework7 handles links and views, but I don't have any ideas on how to fix it. Please anyone with some experience or tips help me out.

2

There are 2 answers

0
Eazicoding On

I found an answer that works on stack overflow a day later (see link below), however I didn't want to bother to answer my own question, but I've decided to do that now.

The solution lies with programmatically scrolling the desired element/section into view with JavaScript scrollIntoView method available on every DOM element.

In a Framework7 app, the scrollable container is the element with .page-content class, not the html or body tag. This was the cause of the shortcomings of the classic method which presupposes the scrollable container to be the body tag, unlike JavaScript scrollIntoView method which looks for the closest scrollable ancestor of the section.

document.querySelector(". section").scrollIntoView();

Solution sourced from Armando Pérez Marqués answer

0
Lixas On

My way of solving this was

var $$ = Dom7;

$$(document).on('click', 'a', function(event) {
   // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // animate scroll effect
      $$('.page-content').scrollTop(
        $$(hash).offset().top-65, 
        800, 
        function(){
            window.location.hash = hash;
            
        }
      )

    } // End if
});