maxum
maxum

Reputation: 2915

DIV position using Jquery .position doesn't seem to work

I have an error message that I would like to position over the offending li element. I am getting the position of the element and trying to place a hidden div and half opacity over the top of it. Below is what I have so far..

script

 function error_msg(error,id)
 {
 var p = $(id);
var position = p.position();
$(".overlay").css("left: " + position.left + ", top: " + position.top);
$(".overlay").width(p.innerWidth())  
$(".overlay").height(p.innerHeight())
$(".overlay").fadeIn();
 }  

(id is the element id of the li) this does calculate the correct position but it is ignored.

css

  div.overlay {
  font-size: 20px;
  margin-bottom: -1px;
  background-color: rgba(247, 40, 40, 0.6);
  z-index: 10000;     
  border-bottom: 2px solid #000;
  border-top: 1px solid #4a4b4d;
  }

Html

<ul>
<div class="overlay" style="position: absolute; display: none;" id="error_li" onClick="hideMsg()">some error message</div>
<li id="item_1">stuff</li>
<li id="item_2">stuff</li>
<li id="item_3">stuff</li>
<li id="item_4">stuff</li>
<li id="item_5">stuff</li>
</ul>

When ever this fires it always puts the div at the top of the list or position 0,0. Any clues where I'm going wrong?

Upvotes: 0

Views: 2338

Answers (2)

nfechner
nfechner

Reputation: 17525

If you use Firebug, you can do a console.log(position); to figure out, if you are reading the position correct.

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237817

$(".overlay").css("left: " + position.left + ", top: " + position.top);

That line is invalid. css does not set the style attribute: it adds styles to the element directly.

You have two ways of doing this. The first is to use multiple css calls (you can chain them for performance & readability):

$('.overlay').css('left', position.left).css('top', position.top);

Alternatively, you can pass an object to css:

$('.overlay').css({
    left: position.left,
    top: position.top
});

Since those are the only properties of the position object, you could even pass that in:

$('.overlay').css(position);

Upvotes: 4

Related Questions