Search code examples
durandal

prevent anchor tag from navigating to home page


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


Solution

  • 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();
    };