0

I pulled a snippet of JS from a response to: How can I make content appear beneath a fixed DIV element?

The JS works great but only when the page first loads, if the screen size changes for whatever reason, the rendered page is then in error until refreshed.

I currently have this:

$(document).ready(function() {
  var contentPlacement = $('#topMenu').position().top + $('#topMenu').height();
  $('body').css('margin-top',contentPlacement);
  $('#navWindow, #searchWindow').css('margin-top',-contentPlacement);
});

Is there a way to have the outputted CSS dynamically change at the moment the screen size updates? This will also be helpful while developing the site.

This will be for displaying the content on my page underneath a fixed menu.

UPDATE

The sample of the site is located here: http://wp19.knowgreaterpartnership.com/

Jeff Sydor
  • 307
  • 1
  • 10
  • 1
    Y'all ever heard of media queries? – MaKR Jun 28 '19 at 15:08
  • 2
    Can you share your website? You don't need JS nor jQuery for this. CSS alone should be able to do the trick. – Mr. Hugo Jun 28 '19 at 15:08
  • css `vw` and `vh` measurements usually fix fullscreen problems – GrafiCode Jun 28 '19 at 15:09
  • Yeah, media queries are what i was using, but it's annoying to use when I need to change them so frequently and for every instance when something is added/changed. At lease with this, the browser can calculate what that perfect value needs to be. – Jeff Sydor Jun 28 '19 at 15:11
  • @GrafiCodeStudio the View width and view height can be set by the browsers meta and is often unreliable. – Eric Hodonsky Jun 28 '19 at 15:40

2 Answers2

1

Additionally to the ready Callback function you can also use jquery.resize. You just have to execute the same code on the resize callback. Resize will be called every time the window size changes.

For the sake of less code redundancy I introduced a new method adjustContent:

$(document).ready(adjustContent);

$(window).resize(adjustContent);

function adjustContent() {
    var contentPlacement = $('#topMenu').position().top + $('#topMenu').height();
    $('body').css('margin-top',contentPlacement);
    $('#navWindow, #searchWindow').css('margin-top',-contentPlacement);
}
Guillermo
  • 764
  • 6
  • 15
0

I know you're asking about using jQuery to change CSS, but what you really should be doing is using Media Queries for your css so that it's declarative instead of script/event initiated.

Ex: (https://www.w3schools.com/Css/css3_mediaqueries_ex.asp )

/* Set the background color of body to tan */
body {
  background-color: tan;
}

/* On screens that are 992px or less, set the background color to blue */
@media screen and (max-width: 992px) {
  body {
    background-color: blue;
  }
}

/* On screens that are 600px or less, set the background color to olive */
@media screen and (max-width: 600px) {
  body {
    background-color: olive;
  }
}
Eric Hodonsky
  • 5,617
  • 4
  • 26
  • 36