Add new element to DOM on action in Ember

991 views Asked by At

What would be a proper way to dynamically add a new element to DOM in Ember? For example a tooltip. Currently I render all tooltips right away, but they're hidden and only shown on mouse over, which takes time to render anyways. I could use jquery or plain JS to append element on event and it would probably work, but would it be the most efficient way to do so? Also would be nice to still be able to use a template, so code wouldn't be too large.

1

There are 1 answers

5
stolli On

Directly manipulating the DOM is very much a no-no in an Ember app. You want to make it an Ember component of course!

In any page, route, or component template:

{{#if showTooltip}}    
  {{tooltip text=someMessage}}
{{/if}}

and then in, say, /pods/components/tooltip/component.js

export default Ember.Component.extend({
  text: 'hello there! this is a tooltip'
})

and finally a template for the component /pods/component/tooltip/template.hbs

<span class='tooltip-text'>{{text}}</span>

In your controlling context, say a component or a controller, you might have a handler like this then:

onMouseOver (event) {
  this.set('showTooltip', true)
},

onMouseOut (event) {
  this.set('showTooltip', false)
}

And these handlers could be actions or just native events on a component, triggered based on whatever DOM interaction event you want.

This will give you a template based tool-tip that only renders in the controlling context if you've set the showTooltip property to true. It's as close to what you are asking for as you are going to get in an Ember app.