Ollie
Ollie

Reputation: 1134

Changing jQuery based on screensize

I'm currently using a small plugin (jTruncate) that truncates text when it's over a certain threshold of letters - and I was wondering, can I tie that letter threshold to the screen size?

For example

if screensize under <320 px - show 45 Letters
if screensize under <500 px - show 60 Letters

$().ready(function() {  
    $('#recent').jTruncate
    ({  
        length: 45,
        moreText: [""],
    });
});

Upvotes: 1

Views: 375

Answers (3)

rlemon
rlemon

Reputation: 17666

http://jsfiddle.net/EwNxR/8/ here is a demo with js. However I do suggest using media-queries as Jimbo noted in his answer.

Important things to note in the code:
1) You will likely want to listen for page resize and action on it. There is no point in running the code once on page load then not when the user resizes their browser window.
2) You shouldn't have to use the jQuery $(window).height() if IE6 is not a concern. Use window.innerHeight.

window.onresize = resizer;
function resizer() {
    if (window.innerWidth < 960) {
        $('#recent').jTruncate({
            length: 45,
            moreText: [""],
        });
    }
}

I'm not 100% familiar with the plugin, however if the options are structured like jQuery plugins generally are you should be able to initialize it on page load then just change the length value.

var recent = $('#recent'),
    defaultLength = 256; // default, can be whatever.
window.onresize = resizer;
recent.jTruncate({ length: defaultLength, moreText: [""] });
function resizer() {
    if (window.innerWidth < 960) {
        recent.jTruncate("length", 45); // don't re-init the plugin, just change the option.
    } else {
        recent.jTruncate("length", defaultLength); // page resized and truncating is no longer needed to be shorter.
    }
}

Upvotes: 2

Jimbo Jones
Jimbo Jones

Reputation: 563

Just as an alternative to Javascript, you could use a CSS media query and wrap the last 15 chars in a span which is hidden in the smaller resolution.

Upvotes: 2

Naftali
Naftali

Reputation: 146302

Just use window.

var win_width = $(window).width();
var win_height = $(window).height();

Upvotes: -3

Related Questions