JokerMartini JokerMartini - 2 months ago 9
HTML Question

html scroll to flickers page

Why when a user clicks a link in the list does it cause the browser to flicker? This seems to be very apparent when a user clicks the same 'link' twice. Is there a way for me to remove this from happening?

It also appears to happen if you click a link that scrolls upwards instead of down. To test this click the list item 'Test' and then click 'Why'

https://jsfiddle.net/JokerMartini/9vne9423/

Here is the main JS bits which are doing all the work...

JS

function scroll_to_element(element) {
$('html, body').animate({scrollTop: $(element).offset().top}, 500);
}

$(window).ready(function() {

$(".nav-title").click(function() {
var target = $(this);

// get data-filter text
var title = target.data('title').toLowerCase();

// collect section titles
sections = $( ".section-title" );

// loop through and scroll to valid section
for (i = 0; i < sections.length; i++) {
var section = $(sections[i]);
var section_title = section.data('title').toLowerCase();

if (section_title === title) {
scroll_to_element(section)
// console.log(target);
}
}
});
});

Answer

You should prevent the default behavior of the anchor tag before invoking your custom functionality:

$(".nav-title").click(function(e) {
    e.preventDefault();
});

Updated Fiddle

Comments