Kejdi Rama
Kejdi Rama

Reputation: 1

scrollIntoView not working: refreshes the page

HTML:

<a href="" class="hero-btn" 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 scroll to my div. But it scrolls and then refreshes the page.

Upvotes: -1

Views: 99

Answers (1)

Nick
Nick

Reputation: 1639

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="#" class="hero-btn" onClick="document.getElementById('middle').scrollIntoView(); return false;">Get Started</a>
<div id="middle"></div>

I haven't tested it but it should works

Upvotes: 0

Related Questions