Wojciech Maj
Wojciech Maj

Reputation: 1122

Dynamically created "read more" link expands all the content instead of just one

What I was trying to code was the following:

  1. Find every div of given class
  2. If one of them happens to be higher than my maximum, make it 75px high and hide overflow, and add a "read more link" after this specific oversized element.
  3. Make the link work...

I succeeded up to no. 2. However, the link on click expands all the content in all divs starting from the one it should expand downwards.

What am I doing wrong?

Thanks in advance!

        $(function() {
            $('.text').each(function() {
                var content = $(this).find('.text_content');
                if(content.outerHeight() >75) {
                    content.css('height','75px').css('overflow','hidden');
                    content.after('<div class="text_readmore">read more</div>');
                    $('.text_readmore').each(function() {
                        $(this).click(function() {
                            content.css('height','').css('overflow','');
                        });
                    });
                }
            });
        });

Upvotes: 1

Views: 1585

Answers (1)

Blazemonger
Blazemonger

Reputation: 93003

You're using the content variable inside your .click handler, which isn't point to what you want. You can also refactor your code so that .click handler is defined once for all such text_readmore links, for efficiency.

Try something like this:

$(function() {
    $('.text').each(function() {
        var content = $(this).find('.text_content');
        if(content.outerHeight() >75) {
            content.css('height','75px').css('overflow','hidden');
            content.after('<div class="text_readmore">read more</div>');
        }
    });
});

$(document).on('click', '.text_readmore', function() { // event delegation
    $(this).closest('.text_content').css('height','').css('overflow','');
});

If you're using a version of jQuery before 1.7 (which is when .on was added), use .delegate instead:

$(document).delegate('.text_readmore', 'click', function() { // event delegation
    $(this).closest('.text_content').css('height','').css('overflow','');
});

Upvotes: 1

Related Questions