jQuery if condition not working when screen is small (mobile)

163
August 01, 2018, at 3:20 PM

i have a simple jquery condition which is simply checking a css value as shown below

if ($('.classname').css("width") < '60%')  {
$.lightbox($'#popupbox'), {});
$('.classname').css({
  'width': '66%'
}
}

This is fired as part of a larger javascript function, Easy peasy right?

It works perfectly fine when the screen size is larger than 1029px

However, anything less and it seems to not be able to "detect" that the condition is true and it doesn't need to fire the popup, and will fire the popup over and over everytime the function is executed.

I had thought this was caused directly by the screen size, but it shouldn't be, because the css value is in % and it is => 60% regardless of screen size.

Any advice would be appreciated.

Answer 1

From the documentation .css() is returning a «a computed style property».

For a width, that is in pixels. That is the current rendered width.

if you want to check if an element's width is 60% (or less) of another, you'll have to do the math. Something like:

var inner_element_width = $('.inner').css("width");
var outer_element_width = $('.outer').css("width");
if (inner_element_width <= (outer_element_width * 0.6))  {
  // Do something
}
Rent Charter Buses Company
READ ALSO
Accessing Table in Partial View

Accessing Table in Partial View

I'm trying to edit a table by adding rows, but running into an issue with the the partial view not being fully rendered (This is my assumption)

198
How to remove value by id from JSON file?

How to remove value by id from JSON file?

I have small project where I need to be able to insert/edit/delete records from JSON fileI use http://myjson

134
Image flickers only once when swapped with another one

Image flickers only once when swapped with another one

I have this annoying problem with my codeI am building a simple page and I have an image that must change while scrolling down the page

143
How to make button group behave like button stages

How to make button group behave like button stages

I have some button group and on click on it it's toggleClass to green but anywhere if you click its turned to default color

157