Mygel Bergstresser
Mygel Bergstresser

Reputation: 90

How to stop a page from jumping to the top after clicking link

I have a filter and when you try to change the level of experience the page goes to the very top. my code looks like this:

Visual: https://i.sstatic.net/CZ3Y6.jpg

<ul class="SecondNavigation">
<li>
    <nav class="CategoriesNaviation">
        <h3>Experience Filter</h3>

        <ul>
            <li>
                <a href="/">
                    <i class="fa fa-list fa-fw fa-2x"></i>
                    <span>No Filter</span>
                </a>
            </li>

            <li class="Selected">
                <a href="/Beginner/">
                    <i class="fa fa-list fa-fw fa-2x"></i>
                    <span>Beginner</span>
                </a>
            </li>
            <li>
                <a href="/Intermediate/">
                    <i class="fa fa-list fa-fw fa-2x"></i>
                    <span>Intermediate</span>
                </a>
            </li>
            <li>
                <a href="/Advance/">
                    <i class="fa fa-list fa-fw fa-2x"></i>
                    <span>Advance</span>
                </a>
            </li>
        </ul>
    </nav>
</li>

Question: Is there a way to disable the page from moving to the top after the user clicks on the anchor?

Upvotes: 0

Views: 3380

Answers (1)

Terry
Terry

Reputation: 66113

You can use:

Both will have the effect of prevent the default behavior of internal anchor links from navigating to the top of the page. Example usage, as has been demonstrated on SO before:

var links = document.querySelectorAll("a"),
    pd = function(e) {
        e.preventDefault ? e.preventDefault() : e.returnValue = false;

    };

links.addEventListener('click', pd, false);

If you're using jQuery, you can do it like this:

var links = $('a');
links.click(function(e) {
    e.preventDefault(); // Can be used anywhere
});

Important to note that if you choose to use return false, it has to be on the last line in the function, otherwise it will stop all downstream code from being executed:

var links = $('a');
links.click(function() {
    // Your code here
    // ...

    return false; // Must be on the last line
});

Perhaps some bedtime reading?

Upvotes: 1

Related Questions