1

I currently am using jQuery and ES6 to do a simple Read Me toggle. Here is my code and it works on more than one read more on the page.

class ReadMore {
    constructor(cfg) {
        this.toggle = $(cfg.el).find('.read-more-toggle');
        var toggleText = $('.read-more-toggle').text().split(" ")[0];

        $('.read-more-toggle').click(function(e) {
            e.preventDefault();

            if ($(this).hasClass("read-less-toggle")) {
                $(this).parent().prev(".read-more").hide()
                $(this).removeClass("read-less-toggle")
                $(this).text(toggleText + " More");
            } else {
                $(this).parent().prev(".read-more").show();
                $(this).text(toggleText + " Less");
                $(this).addClass("read-less-toggle");
            }
        });
    }
}

export default ReadMore;

I was wondering why is it that when I use this.toggle it only works on one instance of the read-more and not of another instance, but when I use $('.read-more-toggle') directly it works. I think I'm a bit confused by the scope.

1
  • There doesn't seem to be any advantage from using a class here. It doesn't have any methods, and you don't even seem to use the .toggle field - so if you don't need to store the instances, just don't create them in the first place and use a simple function initReadMore(cfg) instead of that constructor. Commented Jun 11, 2016 at 16:05

1 Answer 1

1

this (and therefore by implication, $(this)) refers to the single .read-more-toggle element which raised the click event.

$('.read-more-toggle') refers to all .read-more-toggle elements found within the current document.

Hence the former affects only one element, while the latter affects all of them.

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

1 Comment

So what is i want to store the read more selector in a var so it doesnt need to access the dom each time but refers to all the read-more-toggle elements in the dom

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.