Bill Noble
Bill Noble

Reputation: 6734

How can I use jQuery with Ionic 2?

I have been given some JQuery code that I need to use with my ionic 2 project. How can I include it and the JQuery library?

The code looks like this (this is just a part of it):

// on 'Left Down' button click:
jQuery('body').on('click', '.left-down', function (e) {
  
	jQuery('body #top-scale').stop();
	jQuery('body .right-hand-weight').stop();
	jQuery('body .left-hand-weight').stop();
	//top of scale animation
	jQuery("body #top-scale").animate({
  		transform: "rotate("+ setWeights(3,0) +"deg)"
	})
	

		//===rotate + reposition each weight *** 
		jQuery("body .right-hand-weight").animate({
		 	transform:"rotate("+ getWeights() +"deg) translateX("+getX("right")+"px,"+getY("right")+"px)"
		 })

		jQuery("body .left-hand-weight").animate({
		 	transform:"rotate("+ getWeights() +"deg) translateX("+getX("left")+"px,"+getY("left")+"px)"
		 })

		//console.log(getWeights());

		// set number value in weight 
		jQuery( "body .text-1" ).text( leftWeightPercentage );

});

I was thinking of putting a script src tag in the index.htm for the JQuery library and the jquery code file I have been given, but I can't work out how to import the code into my ionic 2 project.

Upvotes: 17

Views: 28890

Answers (1)

Francisco Sandi
Francisco Sandi

Reputation: 1013

Updated at: 12/04/2018

1. First of all, install jQuery in your ionic project:

$ npm install jquery --save

2. After that, install jQuery global derectory to typings (so you can import it):

$ npm install @types/jquery

3. Then, you can import JQuery in the page/component where you want to use it (for example: home.ts), with the following code:

import * as $ from 'jquery'

And that's all, now it should be working.


Checking:

To check if it worked , you can simply try the following:

1. In your component/page (for example: home.html) add an element with an specific id (in this case: myButton), and a method:

<button id="myButton" (click)="changeTextColor()">Click Me!</button>

2. In your component/page: (in this case: home.ts) add the method:

changeColor(){ $('#myButton').text('white'); }

And that should change the text of the button.

Upvotes: 50

Related Questions