Question

In my Backbone app I have a root route which is just blank. In some of my views I have <a> tags for UI elements that I have registered in the view's events object. In order to have properly formed markup I need to have href='#' in these anchors but I don't want them to go to the root of my app.

It seems like for all <a>s that I don't want to go to the root, I have to always call evt.preventDefault(). I would like to confirm this and find out if there are other/better options available.

I'm aware I could make a <div> or <span> with cursor: pointer but my gut is telling me I want these to semantically be anchors.

Was it helpful?

Solution

You have three options:

  • always return false in the handler or call preventDefault on the event
  • use href="javascript:void(0)" (which hurts my eyes)
  • place some sort of special class or data attribute on the links that you don't want to be navigable and create some generic handler that always prevents the navigation
  • use <button> whenever you are using <a> with a dummy href right now

In my opinion, the last option is the best, because it's clear that these GUI elements perform some action that is 'local' to the content you are showing at the moment, while links (or rather: URIs they link to) are by design representing different resource (and content).

OTHER TIPS

I had to do this recently to an existing project, so I'd like to provide a conditional alternative to the selected answer... Depending on the complexity of the project in question, there is another option that could in my opinion be more efficient.

Quite simply:

  • Make it possible to target all applicable links:

    Example: add class="no-link" to all relevant <a> elements.

  • Disable typical link functionality by targeting the appropriate CSS selector.

    Example: apply the usual e.preventDefault() override to elements matching $('a[href="#"].no-link')

JS Bin example.

That said, most often simpler is better.. If you don't need to add a custom class to numerous links on a page, then don't. :) Also be very careful when using this, having insufficiently specific jQuery selectors could result in some links being disabled when you don't expect them to be.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top