Search code examples
jquerypreventdefault

jQuery preventDefault not prevent anchor's behaviour


I have a menu that filters through categories and hides or displays whatever category is clicked on. The filtering is working fine but for some reason I can't stop the anchor's default behaviour. The anchor has a '#' and every time it is clicked it takes you to the top of the page which is no good UX. I need it to stay where it is so that filtering happens without moving the user to the top of the page. Any help would be appreciated. Thanks,

Here is my jquery:

$(".portfolio-nav li:first-child").addClass("active");
//Filter through Categories
$(".portfolio-nav ul li a").click(function(e){
    e.preventDefault();
    //Add class active to the nav item
    $(".portfolio-nav li").removeClass("active");
    $(this).parent().addClass("active");
    //Get the filter data
    var filter = $(this).data('filter');
    //set 'All' filter value
    if(filter == '*'){
            filter = 'category';
    }
    //Hide all categories
    $(".categories").children("div").not('.'+filter).css({'width':'0', 'height':'0', 'opacity':'0', 'padding':'0', 'margin':'0'});
    //Fade In filters after categories fade out
    $(".categories").children('.'+filter).css({'width':'48%', 'height':'300px', 'opacity':'1', 'padding':'0', 'margin':'1%'});
});

Here is my markup:

<div class="portfolio-nav block row">
    <ul class="inline center block">
        <li class="pills slow">
            <a href="#" data-filter="*">
                All
            </a>
        </li>
        <li class="pills slow">
            <a href="#" data-filter="websites">
                Websites
            </a>
        </li>
        <li class="pills slow">
            <a href="#" data-filter="ecommerce">
                E-Commerce
            </a>
        </li>
        <li class="pills slow">
            <a href="#" data-filter="apps">
                Apps
            </a>
        </li>
        <li class="pills slow">
            <a href="#" data-filter="tools">
                Tools
            </a>
        </li>
    </ul>
</div>

Solution

  • It appears that this piece of code on line 93 of main.js was causing the anchor tag to jump to the top of the page:

    var a=document.getElementsByTagName("a");
    for(var i=0;i<a.length;i++) {
        if(!a[i].onclick && a[i].getAttribute("target") != "_blank") {
            a[i].onclick=function() {
            window.location=this.getAttribute("href");
            return false; 
            }
        }
    }
    

    Change the click handler to not set the window.location for an essentially blank href:

    a[i].onclick=function() {
        if(this.getAttribute("href") !== '#') {
            window.location=this.getAttribute("href");
            return false; 
        }
    }
    

    And you'll be good to go!