I have this code working, but it seems clunky to me, is there a way to simplify? The gist of it is I’m checking the page width when the page loads and showing or hiding a div based on that (based on if the browser is wider or skinnier than 480 pixels). Then if the user resizes the browser window, I check the width again and show/hide the proper divs. Anyway this could be simplified with jquery or just js?
function pageWidth() {
return window.innerWidth != null? window.innerWidth: document.body != null? document.body.clientWidth:null;
}
//Show/hide the correct div when the page loads
if (pageWidth() >= 480) {
$(".siteSearchDropdown").css("display", "none");
$(".siteSearchSelect").css("display", "block");
}
if (pageWidth() < 480) {
$(".siteSearchDropdown").css("display", "block");
$(".siteSearchSelect").css("display", "none");
}
// Show/hide the correct dropdown when the browser window is resized
$(window).resize(function() {
if (pageWidth() >= 480) {
$(".siteSearchDropdown").css("display", "none");
$(".siteSearchSelect").css("display", "block");
}
if (pageWidth() < 480) {
$(".siteSearchDropdown").css("display", "block");
$(".siteSearchSelect").css("display", "none");
}
});
Rather than writing the code twice, write it once inside the
window.resizeevent handler and then trigger aresizeevent on thewindowelement:Also, since this code will run many times when someone resizes their browser you should optimize your code by caching the selectors:
Note: I mentioned how
resizeevent handler code is run many times when the browser is resized. To test this for yourself, just add this code to a page and watch your developer console fly:After looking at the code again you can optimize further by using an
if/elsestatement rather than running thepageWidth()function twice: