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) + '...');
                }
            }
        });
    });
2
  • well, are you changing the width to more than 1280? Commented Jan 15, 2014 at 17:20
  • write console.log($(window).width()) above the if condition. What does that give you? a jsfiddle would help us. Commented Jan 15, 2014 at 17:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

the problem is now that the script only work when i resize the window, but i want on load page.
can i do something like (document).load ??
Forgot you had that in the <head>. Fixed that too.
its working now.... you are the man... heheh... thank you ver much for this great help... +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.