jQuery preventDefault in a function
javascript, jquery
Solution
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>
Problem
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); }); ```