Search code examples
jquerywindow-resizejquery-resizable

jQuery resize only working partially


OK, first off, I am NOT really familiar with javascript, so please forgive if this seems a really dumb question...

Here's my code to dynamically resize header items depending on window height (logo, title) and navigation bar depending on width of dynamically sized logo & title:

function titlesize (){
  var winsize = {
    width: document.documentElement.clientWidth || window.innerWidth || document.body.offsetWidth,
    height: document.documentElement.clientHeight || window.innerHeight || document.body.offsetHeight
  };

  var titlefont = $(".title");
  var logo= $(".logo");
  var logow = winsize.height * 0.2;
  var logoh = winsize.height * 0.15;
  var titlefontsize = winsize.height * 0.03;
  var titlew = titlefontsize * 7;

  if (winsize.height > 580) {
    logo.css({width: logow, height: logoh});
    titlefont.css('font-size', function(){return (titlefontsize);});
    titlefont.css('width', function(){return (titlew);});
  }
  else {
    var logow = "150";
    var logoh = "100";
    var titlew = "122.5";
    logo.css({width: logow, height: logoh});
    titlefont.css({'font-size': "17.5px", width: titlew});
  }

  if ((winsize.width > 480) && ((winsize.width * 0.9) < (logow + titlew + 420))) {
    $("nav").css({float: "left"});
  }
}
$(document).ready(function() {titlesize(); $(window).resize(titlesize);$(window).load(titlesize);});

Explained: I have a title logo and text dynamically resized according to window height rather than the usual width, so that the overall header does not take too much of the screen (especially on mobile devices in landscape).

Navigation bar will then be placed: top right if there is enough space (default), or below header (float:left).

The problem is: Window resizing does resize logo and text just fine, but not the nav bar. That does only react on reload, not on resize. Is there any reason why?

I suspect it is because of the dependency of those dynamic variables deriving from the first if else statement. I'm pretty sure there is a simple solution, but what?

Thanks for any help.

PS: tried to make a jsfiddle, but it gives me POST error (no idea why, there is no form submit or anything like that)

EDIT & SOLUTION

Figured out why it did not work: simply made a mistake in the var declarations

I set in the else part of the function vars logow and titlew to fixed values in quotes, thus js took them as text rather than numbers. Hence, the calculation for the nav just messed up. Declaring those vars as numbers (var logow = 150;) did the trick.

Thanks nevertheless for your help and the great hint at media query with heights!


Solution

  • DominicaJune is right. You can use media queries for height:

    http://trentwalton.com/2012/01/11/vertical-media-queries-wide-sites/