AllisonC
AllisonC

Reputation: 3099

Why am I getting the error: Uncaught TypeError: Cannot read property 'left' of undefined

HTML:

<div id="opening_0" style="background-color: #bfbfbf; position: absolute; left: 45px; top: 45px; height: 202.5px; width: 157.5px; overflow: hidden; z-index: 4;" ondrop="drop(event, this)" ondragover="allowDrop(event)" onclick="photos_add_selected_fid(this);">&nbsp;</div>

Javascript:

canvas.style.left = $("#opening_0").style.left - img.width + "px"; 
canvas.style.top = $("#opening_0").style.top - img.height + "px"; 

Why am I getting this error"?

Upvotes: 0

Views: 115

Answers (3)

MMM
MMM

Reputation: 7310

jQuery objects do not have a style property.

If you want to have access to it, either use the vanilla javascript way:

document.getElementById("opening_0").style.left;

...or "unwrap" the jQuery object like so:

$("#opening_0")[0].style.left;

I'd recommend using the first method. Just remember to parse the value by using parseInt().

Upvotes: 0

Nevett
Nevett

Reputation: 996

The error is because $("#opening_0") returns a jQuery object which wraps the matched DOM nodes. To get to the underlying DOM nodes, you can treat it like an array: $("#opening_0")[0] will work, for example.

But, this approach won't work well, since style.left will return a string which could have px or percentage values. You could use $("#opening_0").offset().left instead which will always return a numerical value.

Upvotes: 2

Alex
Alex

Reputation: 10216

Use jQuery's .css() function because thats basically why you use jQuery:

canvas.style.left = parseInt($("#opening_0").css('left')) - img.width + "px"; 

Upvotes: 2

Related Questions