Display Mobile Content with jQuery if statement

When theĀ order of elements in your desktop layout differs from the order of items in your mobile layout, it might be prudent to load items based on the screen size using a jQuery if statement.

This will allow you to be able to use the same IDs and Classes that were applied to your desktop layout, so theming does not need to be re-applied to the mobile layout.

Here is an example loading two Slick Sliders on one page:

jQuery(document).ready(function(){

	
	REL.init();
});


var REL = {};


REL.init = function() {

	
	var viewportWidth = jQuery(window).width(); // get window width

	if (viewportWidth > 600) { // if window width is larger than pixels
	
		jQuery('#content #banners').slick({
			autoplay: true,
			infinite: true,
			dots: false,
			arrows: false
		}); 
	
	} else { // if window is small than pixels
		
		jQuery('.mobile #banners').slick({
			autoplay: true,
			infinite: true,
			dots: false,
			arrows: false
		}); 
		
	}
	

}

This can also be used to load different files based on window width:

(function () {

var viewportWidth = $(window).width();



if (viewportWidth > 1400) {

     $('#wrapper').load('/ajax/largeScreen.php');

} else {

     $('#wrapper').load('/ajax/smallScreen.php');

}

}());

Sourced here.

Display active section of statement in the console:

function checkWidth() {
    var windowSize = jQuery(window).width();

    if (windowSize <= 667) {
        console.log("screen width is less than 667");
        jQuery('.mobile #banners').slick({
			autoplay: true,
			infinite: true,
			dots: false,
			arrows: false
		}); 
    }
    else if (windowSize > 668) {
        console.log("screen width is greater than 668");
        jQuery('#content #banners').slick({
			autoplay: true,
			infinite: true,
			dots: false,
			arrows: false
		}); 
    }
}

// Execute on load
checkWidth();
// Bind event listener
jQuery(window).resize(checkWidth);

Sourced here.

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.