murspieg
murspieg

Reputation: 154

Changing padding top based on another element, using JQuery

I'm trying to adjust padding-top so that page content will overflow based on the height of a menu, which changes responsively. What I have now doesn't work: when menu items collapse to two rows on a small screen size, the content overlays the menu and, of course, the menu's 2nd row doesn't have focus.

<script>  
var heightHeader = $('.fixedheader').height();
$('.scrollcontent').css({ paddingTop : heightHeader + 30 + 'px' });
</script>

Am I missing some code or misusing this? The non-working menu and content example is here http://jsfiddle.net/r5a4ah7p

In my personal html, I call the library within the head tags (is that the correct location?):

<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

Additional question: When the javascript is contained in the html, should it be placed last, eg, after the appropriate for the content? That's what most web examples show.

Many TIA. -murspieg

Upvotes: 0

Views: 1238

Answers (1)

Luuuud
Luuuud

Reputation: 4439

You didn't load in jQuery in your Fiddle. That's the main reason it wasn't working. The other one being you cannot run jQuery code instantly. One simple way of running jQuery would be loading this from and external .js file.

$(document)
.ready(function(){
    // Your jQuery js here
});

<script type="text/javascript" src="/path/to/file.js"></script>

I've updated your fiddle: http://jsfiddle.net/javasluud/r5a4ah7p/2/

-- edit --

Responds to your comment:

  • the code is working, but there are other issues

  • best is including the script at the end of your body.

Ok, I've looked further into your HTML and JS now:

You have a .fixedheader element inside of another .fixedheader. When you use a class selector in jQuery ( $('.fixedheader') ) you'll select all elements with that class. When you call a function like .height() on it, you can't rely on you getting the height of the right element. Better would be using an id ( '<div class="fixedheader" id="fixedheader"> and $('#fixedheader') ) for the outer element, the one of which you want to get the actual height.

This however will still not work. A fixed element lives "outside of the document flow". Therefore it's dimensions aren't taken into account while calculating the dimensions of its parent element. So the outside .fixedheader in your HTML has actually a height of 0. There is no reason for having the inside element a fixed position. After I removed that class in the code it worked like a charm: http://jsfiddle.net/javasluud/r5a4ah7p/3/

Also you're missing the " around the src values of your links.

Upvotes: 2

Related Questions