3

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);
            }
        }
    });
});
JokerMartini
  • 5,674
  • 9
  • 83
  • 193

2 Answers2

5

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

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

Updated Fiddle

APAD1
  • 13,509
  • 8
  • 43
  • 72
1

put href="javascript:void(0);" instead of href="#" attribute in your "What is", "Why" and "Test1" links

jsfiddle

kalym4ik
  • 108
  • 1
  • 10
  • why though? Could you please explain the reasoning? – JokerMartini Sep 06 '16 at 18:09
  • From the one side, `event.preventDefault()` is the best option here because it was developed exactly to prevent default behavior (like jumping to the top of the page in this case) . And `javascript:void(0)` violates [Content Security Policy](https://developer.mozilla.org/en/docs/Security/CSP) on CSP-enabled HTTPS pages. On the other side, using of `href="javascript:void(0)"` can have some advantages. The best description of this approach you can find [here](http://stackoverflow.com/a/138233/2584305) – kalym4ik Sep 06 '16 at 18:22