Tasos
Tasos

Reputation: 7577

Run a jQuery to every element of the same class return undefined

I found a piece of code in pure JS to apply an ellipsis in a text.

function dotify(element) {
    var limit = element.offsetTop + element.offsetHeight;
    var dots = document.createElement('span');
    if (element['data-inner'])
        element.innerHTML = element['data-inner'];
    else
        element['data-inner'] = element.innerHTML;
    dots.appendChild(document.createTextNode('...'));
    element.style.overflow = 'hidden';
    element.appendChild(dots);
    while (dots.offsetTop + dots.offsetHeight > limit) {
        dots.previousSibling.data = dots.previousSibling.data
            .replace(/\W*\w+\W*$/, '')
    }
}

When I apply this code to one element, it works like a charm. However, when I use the each() function to apply it to every element with the same class, I have an undefined error.

jQuery(".product-description").each(function() {
    dotify(jQuery(this));
    onresize = function(){ setTimeout(function() { dotify(jQuery(this)); }, 100); };
});

The following works:

test = jQuery(".product-description")[0]
dotify(test);
onresize = function(){ setTimeout(function() { dotify(test); } 

Upvotes: 0

Views: 37

Answers (2)

Milind Anantwar
Milind Anantwar

Reputation: 82231

donotify method accepts DOM object and you have passed jquery object in each function. passing dom object of current context(i.e. this) in each function will fix the problem:

jQuery(".product-description").each(function() {
  var current_descr = this;
  dotify(current_descr );
  onresize = function(){ setTimeout(function() { dotify(current_descr ); }, 100); };
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You need to pass a dom element reference to dotify, not a jQuery object reference.

jQuery(".product-description").each(function () {
    var el = this;
    dotify(el);
    onresize = function () {
        setTimeout(function () {
            dotify(el);
        }, 100);
    };
});

Note: Not sure what is the purpose of onresize function in the code

Upvotes: 2

Related Questions