santa
santa

Reputation: 12512

JS syntax breaks the page

I have the following code in my external JS file:

var myDiv = $(".myDiv");

if (myDiv.css('left') == 'auto') { 
    var pos = myDiv.position(); 
    myDiv.css({ "left:" + pos.left + "px", "top:" + pos.top + "px" }); 
} 

It appears that the following line breaks my page:

myDiv.css({ "left:" + pos.left + "px", "top:" + pos.top + "px" }); 

If I comment it out everything works fine, except this functionality, obviously.

And if I put the values in alert I get them correctly as well.

alert(pos.left + ' ' + pos.top)

What am I missing?

Upvotes: 1

Views: 58

Answers (3)

MartinHN
MartinHN

Reputation: 19772

You need quotation marks around the values in the object you pass to the .css() function:

myDiv.css({ "left: '" + pos.left + "px'", "top: '" + pos.top + "px'" });

Upvotes: -1

js1568
js1568

Reputation: 7032

Simple fix, use javascript object notation for the css properties. Move the colon outside the quotes:

myDiv.css({ "left": pos.left + "px", "top": pos.top + "px" });

Upvotes: 4

Hemlock
Hemlock

Reputation: 6210

You are trying to create an object by passing in 2 strings.

Should probably look like this:

myDiv.css({
  "left": pos.left + "px",
  "top": pos.top + "px"
});

Upvotes: 7

Related Questions