Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery preventDefault in a function

I have used preventDefault on an element event like this:

$('#element').click(function (e) {
    do stuff...
});

Now, I have a function that takes an argument already in which I would like to use preventDefault but I'm not sure how:

<a href="#services" id="services_link" class="services" onclick="sectionScroll('services')">Services</a>


function sectionScroll(id) {
    history.pushState(null, null, '#' + id);
    $('html, body').animate({
        scrollTop: $("#" + id).offset().top
    }, 1000);
}

I tried using return false instead but this caused some flickering when the link was clicked.

How can I add preventDefault to the above function?

EDIT

My original question was around using preventDefault in a function that has other arguments. I didn't need to use inline javascript in the end (it was looking like there was no way to avoid it), so this is what I used. I think it's quite tidy:

<a href="#services" class="menu-link">Services</a>


   $('.menu-link').click(function (e) {
        e.preventDefault();
        var location = $(this).attr('href');
        history.pushState(null, null, location)
        $('html, body').animate({
            scrollTop: $(location).offset().top
        }, 1000);
    });
like image 484
Alan Shortis Avatar asked Nov 21 '12 22:11

Alan Shortis


1 Answers

Well, if you really want to use inline event handlers (wouldn't recommend it though), try this:

<a href="#services" id="services_link" class="services"
   onclick="sectionScroll('services', event)">Services</a>

<script type="text/javascript">
function sectionScroll(id, e) {
    e.preventDefault();
    history.pushState(null, null, '#' + id);
    $('html, body').animate({
        scrollTop: $("#" + id).offset().top
    }, 1000);
}
</script>
like image 86
Korikulum Avatar answered Oct 08 '22 07:10

Korikulum