Ajit S
Ajit S

Reputation: 1341

CSS through jQuery not applied

I am in a process to make a slideshow responsive. I am using simple jQuery to achieve this. My logic is:

If width of window is < 620, make the changes in CSS through jQuery.
else
set default(fixed) css

I have a element who has top:470px fixed css when the window is of normal size. If the size of the window goes below 620, I've changed this to be relative to the image size (which changes on window resize). Here is my code:

function resizeVideo() {
  var width = $(window).width();
  if(width < 620) {
    $('#controls').css('top', $('img').height());
  }
  else {
    $('#controls').css('top', '470');
  }
}
$(window).resize(resizeVideo);

In this way, the controls would stick to the bottom of the image when size is less than 620. Some of the problems which are stopping me right now are:

  1. Whenever I'm maximizing the window from a size which is less than 620, the images scale back to its original sizes, but the #controls element remains at the same height as it was before maximizing.

  2. When I resize the window to a size greater than 620, then too the #controls stay somewhere around 345px when in actual, the height of the image is greater.

  3. Whenever the image in the slideshow changes and I resize the window at that time, the #controls goes at the top of everything, i.e. it doesn't apply the top: property at all.

I have asked all these queries in on single question because all of them are about the #controls element and I believe that fixing one would automatically fix others. Any pointers would be highly appreciated!

Upvotes: 2

Views: 153

Answers (2)

Tim Vermaelen
Tim Vermaelen

Reputation: 7059

Think you have to wrap a closure function inside .resize() e.g. $(window).resize(function(){ resizeVideo(); });.

Also because the function resizeVideo is not a reference you will have to call it with ()

For the jquery .css() function they've made some css hooks you can use without strings so to apply css it will be: $('#controls').css({top: 470 + "px"});

Upvotes: 1

Sascha Krause
Sascha Krause

Reputation: 307

You need the 'px' suffix when manipulating the css via jQuery.

function resizeVideo() {
  var width = $(window).width();
  if(width < 620) {
    $('#controls').css('top', $('img').height()+'px'); // $.height() returns the height without 'px' - so we need to add it manually
  } else {
    $('#controls').css('top', '470px');
  }
}
$(window).resize(resizeVideo);

Upvotes: 2

Related Questions