1

i have this little script where i try to detect the window size to apply the limit of caracters of an element.

the problem the detection is not working. Always apply the limit of 150.

i have set an alert to look if detect or not, and now i´m sure that he is always apply the same.

can someone help me to find out what is wrong with this script?

here is my code:

$(function () {
        $(".block6 p").each(function (i) {
            len = $(this).text().length;
            if (len > 10) {
                if ($(window).width() <= 1280) {
                    $(this).text($(this).text().substr(0, 150) + '...');
                }
                else if ($(window).width() > 1280) {
                    $(this).text($(this).text().substr(0, 10) + '...');
                }
            }
        });
    });
user2232273
  • 4,898
  • 15
  • 49
  • 75

1 Answers1

4

Your code only runs once, on document.ready. You need to run the test every time the window is resized:

    $(window).on('resize',function() {
        if ($(window).width() <= 1280) {
            $(".block6 p").each(function (i) {
                var len = $(this).text().length;
                if (len > 10) {
                    $(this).text($(this).text().substr(0, 150) + '...');
                }
            });
        } else { //if ($(window).width() > 1280) {
            $(".block6 p").each(function (i) {
                var len = $(this).text().length;
                if (len > 10) {
                    $(this).text($(this).text().substr(0, 10) + '...');
                }
            });
        }
    });

    $(document).ready(function() {
        $(window).trigger('resize');
    }

http://jsfiddle.net/mblase75/6PQ4Q/

That said, you have a problem in that you're altering the text of each element directly, so switching back and forth by resizing the browser will be destructive. I suggest using text-overflow: ellipsis instead if possible.

Community
  • 1
  • 1
Blazemonger
  • 90,923
  • 26
  • 142
  • 180