How to regain focus on specific html element within tab


My package opens a filetype with a tab full of space-pen-rendered HTML elements, and I want to focus on a particular one (a TextEditorView) when the tab is switched to. The layout looks basically like this:

@div class: 'block', =>
  # stuff in between
  @subview 'editorView', new TextEditorView

What I’d like to do is:

  1. On the tab being reclicked, re-selected, whatever, so that it is the active one in the current pane,
  2. Put the focus on the textEditorView so that the cursor is immediately visible and active within that view.

My attempt is as follows:

atom.workspace.observeActivePane (activePane) =>
  @myActivePane = activePane

@myActivePane.observeActiveItem (activeItem) =>
  if activeItem is @bpe

Where @bpe is the pane item corresponding to my View. It works, but only if I don’t change the active pane or move my view to another pane. I’m not sure why, since that code seems to cover it, even if a new pane is added. How can I extend the focusing functionality to cover other panes?


Figured it out. Now it seems to be working after I moved the observeActiveItem clause into the body of observeActivePane, which makes sense, since otherwise it’s only updating a single pane, not every pane.

Strangely, though, atom.workspace.observeActivePaneItem isn’t working at all for this, not even for switching tabs within the same pane. That confuses me greatly.


Strange that observeActivePaneItem isn’t working, that should be perfect for this. What exactly is the problem you’re having with it? It should be as simple as:

atom.workspace.observeActivePaneItem (item) =>
  @editorView.focus() if item is @bpe

If you want to go the other route, make sure you track your subscriptions and clean up after yourself, or you’ll end up subscribing more than once to the same pane.

itemSub = null
paneSub = atom.workspace.observeActivePane (activePane) =>
  itemSub = activePane.observeActiveItem (activeItem) =>
    @editorView.focus() if activeItem is @bpe

And call itemSub?.dispose() and paneSub.dispose() when your item is removed.


The problem I’ve been having is that it simply is not focusing when I switch to the tab; my code is precisely the same as yours. I tried looking into possible issues in the source but it all seems relatively airtight. I might look into it in more depth later today.


Managed to find a workaround for this using the focus JQuery event:

@on 'focus': (event) =>

This seems to work in all cases.