Setup

These commands will generate some files for us. Will be using them to testjQuery with. The component will be called jquer1-test.

Basic jQuery

Keep in mind that when you create a new project with Ember CLI by default jQuery is installed. Take a look at the bower.json file and you should see it listed.

// bower.json
...
"jquery": "^1.11.1",
...

Let's see a quick example. In our component we'll create a button and some text. When the button is triggered we want to fade out the text. This is how we'll do it. First we'll edit the component hbs file.

This component has an age property that is set to 10. Then we have our actions. The pressed action triggers our jQuery which simply fades out the test div. You can learn more about the jQuery API here.

Last thing we need to do for this simple example is simply add the component to our index.

Initialize jQuery

What if we wanted the text to fade in whenever the page loaded. There is a few ways to do this however the most accepted way is to manipulate the didInsertElement event. This event gets triggered when the element of the view has been inserted into the DOM. We can add this event to our component and then manipulate the DOM as we please.

There is one issue though. You may want to wait until everything is rendered in the DOM before you do any manipulation. The easiest way to do that is to use the Ember.run loop. I wrote about the Ember run loop in a previous post so check that out if your want more information.

As an example let's change the component so that when the page loads the text slowly fades out, and after you press the button it fades back in.

As you can see above we now have added a Ember.run.scheduleOnce to our didInsertElement. This should only run once after everything is rendered.

Another good tip is to destroy any event handlers and objects with willDestroyElement. Since we are doing some simple jQuery effects we don't really need it in this example but we'll go ahead and add it anyways.