Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change an element's top position based on height

I have three divs that are set to popup on li:hover using CSS. I want these divs to hover at the same level above their parent li regardless of the height of their content. In order to do so, I'm trying to use jquery to calculate the div's height, then set a negative top value equal to the height of the div. Here's what I have so far:

<script type="text/javascript">
$(document).ready(function() {
var pHeight = $('footer ul ul').height(); //Get height of footer popup
var nHeight = pHeight + "px"; //Calculate new top position based on footer popup height

        $('footer ul ul').css({ //Change top position to equal height of footer popup
            'top' : "-nHeight",
    });
});
</script>

Firebug keeps telling me that there was an error parsing the value for top and the declaration was dropped. Any thoughts?

like image 687
qp2wd Avatar asked Dec 18 '25 04:12

qp2wd


2 Answers

Change

'top' : "-nHeight",

to

'top' : "-" + nHeight

JavaScript does not parse variables inside of strings. I've also removed the , since it's redundant and it will produce an error in IE.

like image 158
Jan Hančič Avatar answered Dec 19 '25 17:12

Jan Hančič


You need to remove the quotes to use the variable, otherwise it's trying to parse the literal string "-nHeight" as a number:

<script type="text/javascript">
$(document).ready(function() {
  var pHeight = $('footer ul ul').height();
  var nHeight = pHeight;    
  $('footer ul ul').css({
     'top' : -nHeight
  });
});
</script>

Or, the more compact version:

<script type="text/javascript">
$(function() {   
  $('footer ul ul').css({ top: -$('footer ul ul').height() });
});
</script>
like image 35
Nick Craver Avatar answered Dec 19 '25 19:12

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!