John Abraham
John Abraham

Reputation: 18781

How to prevent scroll effect from making my screen flicker on scroll

using chrome and ff so far have made a nasty glitch when using scrollTo function? anyone know how to prevent this from happening?
Live Code

HTML

 <ul class="wrapper">
    <li class="listItem"><img src="asset/img/logo.png" ></li>
    <li class="listItem"><a onclick="scrollTo('#container',500);" href="#">Company</a><span> / </span></li>
    <li class="listItem"><a onclick="scrollTo('.flexslider-container',500);" href="#">Service</a><span> / </span></li>
    <li class="listItem"><a onclick="scrollTo('#map',500);" href="#">Map</a><span> / </span></li>
    <li class="listItem"><a onclick="scrollTo('#footer',500);" href="#">Contact</a></li>
    <li class="listItem">
      <p>250-610-9100</p>
    </li>
  </ul>

SCRIPT

<script type="text/javascript">
function scrollTo(o, s) {
    var d = $(o).offset().top;
    $("html:not(:animated),body:not(:animated)").animate({
        scrollTop: d
    }, s);
}
</script>

Upvotes: 2

Views: 1925

Answers (2)

Blender
Blender

Reputation: 298176

You should be attaching events via .on(), not shoving code into the onclick attribute.

The (more) proper solution is to give you links a class:

<a href="..." class="menu-link">...</a>

And then some fancy data attributes:

<a href="..." class="menu-link" data-target="#container" data-duration="500">...</a>

And in your code, add this:

$(document).ready(function() {
  $('.menu-link').on('click', function(event) {
    event.preventDefault();  // <---- This is the magic stuff

    scrollTo($(this).data('target'), $(this).data('duration'));
  });
});

Basically, you give your elements special attributes that can be read with jQuery's .data() function. Then, instead of adding a function call to each link, you attach one magic function to all of them.


If you want to keep your current code (ehh), just add return false; at the end of every onclick attribute:

<a onclick="scrollTo('.flexslider-container',300);return false;" href="#">Service</a>

This prevents the default action from occurring (scrolling to the top of the page).

I recommend my first solution. You aren't doing jQuery any justice if you are only using it to a third of its potential.

Upvotes: 5

Roko C. Buljan
Roko C. Buljan

Reputation: 206102

Use .stop() to clear the animation queue

function scrollTo(o, s) {
        var d = $(o).offset().top;
        $("html:not(:animated),body:not(:animated)").stop().animate({
            scrollTop: d
        }, s);
    }

As talking about anchors you should prevent the default anchor behavior using preventDefault():

$('.wrapper a').on('click', function(e){
    e.preventDefault();
});

Upvotes: 0

Related Questions