Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

top = $this.css("top") returning an object versus element value

I have a HTML object:

<div data-x="1" data-y="1" class="tile empty" style="top: 32px; left: 434px;"> 
   <div class="inner">1:1</div>
</div>

But for some reason... When I access it's top property in jQuery through the following code:

$tile = $('[data-x=1][data-y=1]'); 
top = parseInt( $tile.css("top") );

Then print it using the following:

console.log(top);

It gives me this in the browser:

Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}

I'm quite puzzled on this, I even stripped away the rest of my statement - $img.height() to top since it's being used on another element later on in the coding solution.

I would expect it to return 32px, get parsed and output 32;

like image 865
Jack Hales Avatar asked Apr 23 '19 10:04

Jack Hales


1 Answers

top is a predefined global variable in browsers. It's read-only, so the assignment you're doing didn't work, and what you're seeing is its standard value (the top-level window).

Be sure to:

  1. Give your code a local scope (don't leave your code at global scope), and

  2. Declare your variables in that local scope, and

  3. Use strict mode so that assigning to read-only variables is an error (rather than just not doing anything); strict mode has other useful things, like disabling the horror of implicit globals (that's a post on my anemic little blog).

So for instance:

(function() {
    "use strict";
    // ...
    var $tile = $('[data-x=1][data-y=1]'); 
    var top = parseInt( $tile.css("top") );
    // ...
})();
like image 82
T.J. Crowder Avatar answered Sep 22 '22 01:09

T.J. Crowder