Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass over an element using TypeScript/jQuery

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
    });
}
like image 278
Marcel Avatar asked Jan 21 '13 14:01

Marcel


1 Answers

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.

like image 112
SWeko Avatar answered Sep 28 '22 21:09

SWeko