alej27 alej27 - 1 year ago 55
jQuery Question

Not run script if window's width is smaller than value

I have a responsive website, with some jQuery code, of which some is the following:


All of the
elements above (
...) have a CSS
property value of
, so by default they aren't visible until you click on one of the
elements above (
...) and then the corresponding div is displayed.

However, when the jQuery script runs, it sets the corresponding
value to
. When the viewport's/window's width is smaller than say 400 px, I want the script to display them with
position: fixed;

My suggestion

I've figured out I can display them with fixed position using:

$("#corresponding_ID").css("display", "fixed");

But I still have to not let jQuery run the first script (the one using

Answer Source

Don't set css styles directly this way. As already commented, use e.g. a .visible class and let css media queries decide. Example:

@media screen and (max-width: 399px) {
  .visible {
    display: fixed;
@media screen and (min-width: 400px) {
  .visible {
    display: block;

Then, in your click handler, go as follows:


Also, if your details containers all follow that naming scheme with affixing _details to the id, it'd be easier to put all ids in an array and iterate over that:

  var ids = [ "#D1000C36LPB3", "#D1200C36LPB3", "#D1-3CA36LPB3", "#D1-0CA36LPB3", "#D700S36LPB3", "#D700S24LMB3"];
  for (var i = 0; i < ids.length; i++) {
    $(ids[i]).on('click', function () { $(ids[i]+'_details').addClass('visible'); }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download