Home > Mobile >  scrollIntoView not working: refreshes the page
scrollIntoView not working: refreshes the page

Time:01-08

HTML:

<a href=""  onClick="document.getElementById('middle').scrollIntoView();">Get Started</a>
<div id="middle"></div>

CSS

.hero-btn{
    display: inline-block;
    text-decoration: none;
    color: #fff;
    border: 1px solid #fff;
    padding: 12px 34px;
    font-size: 16px;
    background: transparent;
    position: relative;
    cursor: pointer;
}
.hero-btn:hover{
    border: 1px solid #f44336;
    background: #f44336;
    transition: 1s;
}

I was expecting it to scrroll to my . But it scrolls and then refreshes the page.

CodePudding user response:

The refresh is due to the <a> link default behavior. Give it the attribute href="#" and to prevent automatic default scroll add return false; on the onclick listener like that:

.hero-btn{
    display: inline-block;
    text-decoration: none;
    color: #fff;
    border: 1px solid #fff;
    padding: 12px 34px;
    font-size: 16px;
    background: transparent;
    position: relative;
    cursor: pointer;
}
.hero-btn:hover{
    border: 1px solid #f44336;
    background: #f44336;
    transition: 1s;
}
<a href="#"  onClick="document.getElementById('middle').scrollIntoView(); return false;">Get Started</a>
<div id="middle"></div>

I haven't tested it but it should works

  • Related