6

In my Ember application, how can I jump to an HTML anchor inside one of my Handlebars templates? I created a jsFiddle that shows what I want to accomplish.

Background
Ember's model of navigation through an application uses HTML anchors.

I have the following requirement: when a user clicks on a Handlebar linkTo helper to navigate to a new route destination, the browser should automatically scroll to an anchor inside the Handlebars template associated to that new route destination.

Abdull
  • 23,005
  • 22
  • 116
  • 159
  • what [type of url](http://emberjs.com/guides/routing/specifying-the-location-api/) are you using? By default Ember uses hash (#), which will collide with anchors. Technically, you could use scrollspy (or something similar) if you implement [hashbang (#!)](http://stackoverflow.com/questions/14929170/hashbang-urls-using-ember-js) client urls. – MilkyWayJoe May 10 '13 at 19:35
  • @MilkyWayJoe I'm using Ember's default hash-based navigation. I just gave the history-based navigation a try, but it didn't work in both my own app and my jsFiddle mentioned above (Exception "`No route matched the URL '/_display/'"`)... thank you for the scrollspy and hashbang suggestions which I will now investigate. – Abdull May 10 '13 at 20:07
  • possible duplicate of [Ember.js anchor link](http://stackoverflow.com/questions/18445661/ember-js-anchor-link) – givanse Nov 12 '14 at 05:07

1 Answers1

-1

Use jquery to scroll to a particular section.

$('html,body').animate({
    scrollTop: $("a[name='someAnchor']").offset().top
});

Refer this SO answer regarding the same.

To scroll to the anchor after the view is rendered override the didInsertElement in your definition for your route's View.

Refer this SO answer regarding the same.

App.LonglistView = Ember.View.extend({
    didInsertElement: function() {
        // Place the scroll to anchor code here.
        $('html,body').animate({
            scrollTop: $("a[name='someAnchor']").offset().top
        });
     }
});

Here is a working example in jsfiddle ( I have not added any data models for clarity )

EDIT: You could also use non-jquery way to do the scrolling

document.getElementsByTagName('a')[name='someAnchor'].scrollIntoView()

The jsfiddle example for the same.

Community
  • 1
  • 1
Raghav RV
  • 3,510
  • 2
  • 17
  • 26