Reputation: 1486
I have a regular anchor tag with href attribute set to "#". Normally, this prevents from any navigation but in durandal it navigates me to the home view. How can I stop it from navigating to that view? I can't change the html and stylings. It needs to be that anchor tag. But I can bind a click event to it. Is there any way to cancel navigation in anchor click event?
regards
Upvotes: 2
Views: 4487
Reputation: 18515
Have all your anchor links start with a prefix. Then have in your router.guardRoute
function this:
if (_.startsWith(instruction.fragment, YOUR_PREFIX))
return false;
}
Worked well for me and no need to add anything else to your app views.
PS. _.startsWith
is lodash function. If not using lodash do JS string indexOf or whatever
Upvotes: 0
Reputation: 9965
Bind a click event to it and call event.preventDefault()
<a href="#" id="someAnchor">Example</a>
$(function() {
$('#someAnchor').click(function(event) { event.preventDefault(); });
});
This will prevent the browser from propagating the click event and nothing will happen. But inside the click event you can do whatever logic you want.
If you are using knockout to bind the click event then please refer to this stackoverflow post on how to do it from a knockout binding.
EDIT ** Per Tyrsius' comments its a better practice to use the knockout binding to bind a click event.
So, instead it is recommended you do:
<a href="#" data-bind="click: clickHandler">ClickMe</a>
clickhandler = function (e) {
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
};
Upvotes: 3