user3077601
user3077601

Reputation: 3

Animated scrolling when not using standard <a href> links

Im using div's with a onclick= function. That in turn exectues a confirm box. If users press OK. it redirects using: window.location.hash and auto scrolls to a div id. Auto scroll works fine. But Animated scroll breaks at this point.

Using conventional a href's works fine with animated scrolling.

Im an amateur and pieced togheter the following code from different sources. I will post the code and hopefully someone has the answer.

Code:

function FrontAsNew() {

 if (confirm("No damage allowed") == true) { window.location.hash = "#side"; }
 else { window.location.hash = "#front"; } 

}

<div id="cosmetics_box" style="cursor:hand; cursor:pointer;" onclick="FrontAsNew()">As new</div>

Animated scroll script: 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" ></script>
<script>
$('div').click(function(){
$('html, body').animate({
    scrollTop: $( $(this).attr('href') ).offset().top
}, 2000);
return false;
});

So in short: Animated scrolling works fine with conventional a href links. But when using divs as links that exectue a function that uses location.hash the animated scrolling breaks.

Thanks for any help in advance!

Upvotes: 0

Views: 126

Answers (1)

Chase Rocker
Chase Rocker

Reputation: 1908

Try something like this:

function FrontAsNew() {

 if (confirm("No damage allowed") == true) { 
   scrollToTopById('side');
 }
 else { 
   scrollToTopById('front');
 } 

}

function scrollToTopById(id) {
   $('html, body').animate({scrollTop: $('#' + id).offset().top}, 2000);
}

Upvotes: 1

Related Questions