简体   繁体   中英

TypeScript - How to get an HTML element like using dollar sign ($) in Javascript

I have the following javascript code in my page that get an element with the class ".parallax" and calls the javascript method "parallax()". Obviously, I need to do this to make the parallax effect to work.

$('.parallax').parallax();

However, once I'm using my HTML elements in the component template in TypeScript file, I need to call it from the TS file.

So how can I get this element by its class name and call the javascript method in Typescript file?


Obs.: I already tried to do this:

var element = <HTMLElement> document.getElementsByClassName('parallax')[1];
element.parallax();

But the compiler doesn't recognize the method "parallax()", warning me this:

TS2339: Property 'parallax' does not exist on type HTMLElement

$('.parallax').parallax();

If parallax is a JQuery function you need parallax.d.ts :

interface JQuery {
  parallax: any;
}

And I am pretty sure this is what you want.

Thank you for your help, @basarat! I followed your tips, but I needed more information to make it work!

My initial problem was to use the $ (dollar) sign, and I solved it by adding this:

import * as $ from 'jquery';


The import above is the right answer to my main question here. However, it was not enough to make the external Javascript function .parallax() to work. I will show below what I did to make ot work whether someone also needs this answer.

I followed some tips from this StackOverflow answer .

Like basarat said, I created a file named parallax.d.ts , but with the following interface:

interface JQuery {
    parallax():JQuery;
}

Then referenced both parallax and jquery files to my component landingPage.view.ts file:

///<reference path="../../../typings/browser/ambient/jquery/index.d.ts"/>
///<reference path="../../shared/parallax.d.ts"/>

and then edited my component class to this:

export class AppLandingPage implements AfterViewInit {
    static landingPageInitialized = false;

    constructor(private el:ElementRef) {
    }

    ngAfterViewInit() {
        if(!AppLandingPage.landingPageInitialized) {
            jQuery(this.el.nativeElement)
                .find('.parallax')
                .parallax();
            AppLandingPage.landingPageInitialized = true;
        }
    }; 
}

Now, by my understanding, the constructor is referencing the component through the el variable, I use this element in jQuery, find the components with the ".parallax" class, and call the function parallax() to make the parallax framework in JS to run.

I'm not sure if I'm explaining everything as it is, but now it works! Hehe

Thank you again for all your help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM