Matt
Matt

Reputation: 5653

jQuery CSS Positioning

http://jsfiddle.net/mretchin/JEVuX/40/

That's my code. I'm trying to make an input box that takes a number, using the .val() method, and positions the red box with that value with the .css() method. I can't figure it out...? As lame as this sounds, when I wrote it a few hours ago and debugged it in IE, it worked, but when I got home, the same jsfiddle link wasn't functioning on Chrome. Is it just my browser? The code will accept 0 as an attribute, but not anything else.

Thanks for helping!

Upvotes: 0

Views: 61

Answers (5)

Rizwan Mumtaz
Rizwan Mumtaz

Reputation: 3965

Dear when you are working with CSS you need to pass PX with the value.

$("#text").keyup(function () {
      var value = $(this).val(); 
      $("p").text(value);
      $("div").css("left", value+"px");
      $("div").css("top", value+"px");
    }).keyup();​

See this http://jsfiddle.net/JEVuX/86/

Upvotes: 0

charlietfl
charlietfl

Reputation: 171700

The problem is the value is a string , adding 'px' makes the string into a recognizable css value, but jQuery will also take the css values as a number.

http://jsfiddle.net/JEVuX/51/

Upvotes: 1

maxedison
maxedison

Reputation: 17573

The problem is that .val() returns a string. One way to solve this--as others here have noted--is by appending px to the end of the string. However, you can instead pass a true numeric value to the .css() method, in which case you don't need to append px. I prefer this way of doing it, as it requires less code and leaves things more easily readable.

All you need to do is add a plus sign before $(this).val() in order to coerce it into a number:

var value = +$(this).val()

And then the rest of your code will work fine.

Beyond this specific case, not needing to append px is useful to know because you'll often be grabbing CSS values using methods like .width(), which automatically return a number.

Upvotes: 3

GregL
GregL

Reputation: 38151

You need to set the units for the top and left CSS properties ("px", "em", etc).

E.g. I changed your code to:

$("#text").keyup(function() {
    var value = $(this).val();
    $("p").text(value);
    $("div").css({
        left: value + 'px',
        top: value + 'px'
    });
}).keyup();​

and it worked.

Upvotes: 1

Purag
Purag

Reputation: 17071

You need to specify the unit of measurement:

$("div").css("left", value + "px");
$("div").css("top", value + "px");

Either this or you write px in the input itself. Both of these have been tested in Chrome.

Demo.

Upvotes: 1

Related Questions