Search code examples
jqueryscrollwindowbackbone-views

Display the top of the page in a scrolling window in a backbone view


I have a Backbone view page (or window) that can have long contents which makes vertical scrolling necessary. When this happens, the view port is positioned automatically in the middle of the window rather than at the top. I want it to open at the top of the page whether the page has long contents or not. I have tried several variations of scrollTo but none seem to work. Note that I am using Backbone js and is written in Coffeescript. Here it is:

:coffeescript
  $ ->
    model = new Backbone.Model
      forcastTickInterval: #{xx_interval(@type_well.num_rows)}
      typeWell: #{@type_well.to_json}
      x_labels: #{price_array}
      disc_rate_array: #{disc_rate_array}
      disc_pv10_array: #{disc_pv10_array}
    view = new VGStream.Views.TypeWells.Show(
      model: model
    ).render()
    VGStream.App.router = new VGStream.Routers.Tabs()
    VGStream.App.currentView = view
    Backbone.history.start()

The Tabs Router is rather simple too:

class VGStream.Routers.Tabs extends Backbone.Router
  routes:
    '' : 'index'
    ':name' : 'viewTab'

  index: ->
    firstTab = $('.tab-nav li a').first()
    firstTab.scrollTop(0)
    if firstTab
      @navigate firstTab.attr('href'),
        trigger: true

  viewTab: (name) ->
    selectedTab = $(".tab-nav li a[href='##{name}']").parent()
    unless selectedTab.hasClass 'active'
      $('.tab-nav li.active').removeClass 'active'
      selectedTab.addClass 'active'
      $('.tab').hide()
      $(".tab##{name}").show()
      if VGStream.App.currentView? && VGStream.App.currentView[name]?()
        VGStream.App.currentView[name]()

What is interesting is when I open Chrome Console and type in the following command:

this.scrollTo(0)

The window correctly goes to the top of the page.

I am not sure how to solve this issue.

Thanks in advance for your help.


Solution

  • Appreciate that this is an old question but maybe the below is of some use to people searching old SO questions to answers to their programming problems.

    So, $(document).scrollTop(0); works. It also works fine with a Bootstrap navbar. But what matters is when you call it. You're manipulating the DOM, the window, so this needs to happen after the view is rendered. Check out Backbone.js event after view.render() is finished to see how to fire an event after the view is rendered.

    I'm using Backbone.Marionette so have both onRender and onShow events automatically fired. This works great for me:

      onRender: function(){
        $(document).scrollTop(0);
      }