alej27 alej27 - 1 month ago 5
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:

<script>
$(document).ready(function(){
$("#D1000C36LPB3").click(function(){$("#D1000C36LPB3_details").show();});
$("#D1200C36LPB3").click(function(){$("#D1200C36LPB3_details").show();});
$("#D1-3CA36LPB3").click(function(){$("#D1-3CA36LPB3_details").show();});
$("#D1-0CA36LPB3").click(function(){$("#D1-0CA36LPB3_details").show();});
$("#D700S36LPB3").click(function(){$("#D700S36LPB3_details").show();});
$("#D700S24LMB3").click(function(){$("#D700S24LMB3_details").show();});
});
</script>


All of the
div
elements above (
#D1000C36LPB3_details
,
#D1200C36LPB3_details
,
#D1-3CA36LPB3_details
...) have a CSS
display
property value of
none
, so by default they aren't visible until you click on one of the
div
elements above (
#D1000C36LPB3
,
#D1200C36LPB3
,
#D1-3CA36LPB3
...) and then the corresponding div is displayed.

However, when the jQuery script runs, it sets the corresponding
div
display
value to
block
. 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
.show()
).

Answer

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:

$("#D1000C36LPB3").click(function(){$("#D1000C36LPB3_details").addClass('visible');});

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:

$(document).ready(function(){
  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'); }
  }
};