Eric Wood
Eric Wood

Reputation: 589

Loading jQuery based on viewport width

I have an events calendar that shows all the days of the week in the top row. The calendar itself is responsive, but when it's shrunken down for mobile, the days of the week extend outside of their boxes, and overlap each other – which also creates some width overflow.

I would like to use jQuery to change "Sunday" to "S" when viewed on mobile, but I'm not sure how to go about doing that.

Using the ".replaceWith" command, I've managed to get part of it to work. I just can't figure out how to trigger this script based on the browser width.

Here's my code so far:

$(window).resize(function() {
    if ($(window).width() < 950) {
        $( "div.sunday" ).replaceWith( "S" );
        $( "div.monday" ).replaceWith( "M" );
        $( "div.tuesday" ).replaceWith( "T" );
        $( "div.wednesday" ).replaceWith( "W" );
        $( "div.thursday" ).replaceWith( "T" );
        $( "div.friday" ).replaceWith( "F" );
        $( "div.saturday" ).replaceWith( "S" );
    }
}

Here's the fiddle: http://jsfiddle.net/CN8Gs/1/

Upvotes: 2

Views: 3102

Answers (2)

Hackerman
Hackerman

Reputation: 12305

Just try this:

$(window).resize(function() {
console.log($(window).width());
if ($(window).width() < 950) {
    $( "div.sunday" ).text( "S" );
    $( "div.monday" ).text( "M" );
    $( "div.tuesday" ).text( "T" );
    $( "div.wednesday" ).text( "W" );
    $( "div.thursday" ).text( "T" );
    $( "div.friday" ).text( "F" );
    $( "div.saturday" ).text( "S" );
}
else
{
    $( "div.sunday" ).text( "Sunday" );
    $( "div.monday" ).text( "Monday" );
    $( "div.tuesday" ).text( "Tuesday" );
    $( "div.wednesday" ).text( "Wednesday" );
    $( "div.thursday" ).text( "Thursday" );
    $( "div.friday" ).text( "Friday" );
    $( "div.saturday" ).text( "Saturday" );
 }
});
$(window).trigger('resize');

JSFiddle demo

Upvotes: 5

Paul Sasik
Paul Sasik

Reputation: 81459

This will work both ways: Fiddle sample here... (Run and resize the Result window. 950 is pretty wide actually. You may want to decrease the width for a more realistic test.)

$(window).resize(function() {
    if ($(window).width() < 950) {
        $( "div.sunday" ).html("S");
        $( "div.monday" ).html( "M" );
        $( "div.tuesday" ).html( "T" );
        $( "div.wednesday" ).html( "W" );
        $( "div.thursday" ).html( "T" );
        $( "div.friday" ).html( "F" );
        $( "div.saturday" ).html( "S" );
    } else {
        $( "div.sunday" ).html("Sunday");
        $( "div.monday" ).html( "Monday" );
        $( "div.tuesday" ).html( "Tuesday" );
        $( "div.wednesday" ).html( "Wednesday" );
        $( "div.thursday" ).html( "Thursday" );
        $( "div.friday" ).html( "Friday" );
        $( "div.saturday" ).html( "Saturday" );    
    }
});

Upvotes: 1

Related Questions