6

I am trying to work out the position and the height/width of a DOM element through TypeScript/JQuery. Before TypeScript I simply did something like this:

        function ActOnClick(itemClicked, loadPath) {
            //sample code
            var v1 = itemClicked.offset();
            var v2 = itemClicked.width();
            var v3 = itemClicked.height();

        };

        $(document).ready(function () {

            $("#idCRM").click(function () {
                ActOnClick($("#idCRM"), "/Widgets/GetCRM");
            });
}

where idCRM is a 'section' in my cshtml document (but it could be any div etc.)

Now I am trying to move this code into TypeScript but what type do I expect in the ActOnClick function to come in from the jQuery's $("#idCRM")? Right now I choose 'Element' but a) it doesn't expose width, height etc and b) the ActOnClick call fails caused by the $("#idCRM")!

/// <reference path="../../ScriptsTS/jquery.d.ts" />
function ActOnClick(itemClicked: Element, loadPath: string) {

    var v1 = itemClicked.offset();  <-- FAILS
    var v2 = itemClicked.width();   <-- FAILS
    var v3 = itemClicked.height();  <-- FAILS

};

$(document).ready(function () {

    $("#idCRM").click(function () {
        ActOnClick($("#idCRM"), "/Widgets/GetCRM");  <-- FAILS
    });
}

1 Answer 1

16

If you need the code to just work, you can always use the Any typescript type, like:

function ActOnClick(itemClicked: Any, loadPath: string) {
  var v1 = itemClicked.offset();
  var v2 = itemClicked.width();
  var v3 = itemClicked.height();
};

Typescript basically shuts up on an Any variable, and it won't issue any errors or warnings. However, $("#idCRM") should return an object that implements the JQuery interface, defined in jquery.d.ts, so you should actually use:

function ActOnClick(itemClicked: JQuery, loadPath: string) {
  var v1 = itemClicked.offset();
  var v2 = itemClicked.width();
  var v3 = itemClicked.height();
};

the offset(), width() and height() methods are defined on that interface, and they return Object, number and number, respectively.

Sign up to request clarification or add additional context in comments.

1 Comment

my version (jquery-1.8.d.ts from DefinitelyTyped) exposes a width method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.