Reputation: 4552
As many other threads and external forums suggest, I've tried placing e.preventDefault() (while passing e as parameter, not in code sample) in every place imaginable, but it doesn't prevent the anchor from reloading the page. When I step through the debugger, it will assign every div with scrollNav the click event, but when I click on the div-link it just reloads the page and the debugger does not stop on any lines in the highlightSelection function. Another method I've tried is to use an anonymous function inside this.click and place e.preventDefault() as the first line, but it does nothing.
I also don't really understand why you would want to place e.preventDefault() as so many others have suggested. Isn't it basically saying return false? That may stop a link from reloading the page, but won't it prevent the code in the method from executing?
jQuery(document).ready(function() {
jQuery('.scrollNav').each(initSideNavForSelection);
}); // end ready
function initSideNavForSelection() {
this.click(highlightSelection);
}
function highlightSelection() {
var selectedDataID = this.attr("data-id");
jQuery('.scrollNav').each(function() {
if (this.attr("data-id") === selectedDataID) {
this.addClass("selected");
} else {
this.removeClass("selected");
}
})
}
Upvotes: 2
Views: 1204
Reputation: 9298
There are a few things I had to do to get your codes to run. You can take a link at this fiddle here.
Here's the list:
onclick="Event.stop(event)"
inlined attribute as Event
is undefined.this
with $(this)
in both your initSideNavForSelection()
and highlightSelection()
functions. this
represents a DOM object and $(this)
is a JQuery wrapper around this
. The latter will respond to JQuery methods like .click()
, but not the former.So far, there is no page reload in your fiddle, with or without e.preventDefault()
.
Finally, in addition to event.preventDefault()
, return false
also calls event.stopProgagation()
to prevent the event from bubbling up the DOM, before terminating the callback execution immediately. A call to event.preventDefault()
doesn't terminate the function call immediately.
Upvotes: 1
Reputation: 1733
Add onclick="return false;"
to the anchor.
OR change initSideNavForSelection
function to
this.click(function(e) {
e.preventDefaults();
highlightSelection();
});
either works
Upvotes: 2