Search code examples
jquerychain

jQuery and chaining issue


I'm a jQuery rookie and maybe I'm about to ask a very basic question, but I'm really struggling while figuring out why jQuery chaining doesn't work in my case.

var container = $('#container'),
items = container.find('ul.items'),
moreItems = items.children('li.moreItems');

var config = {
container : container,
items : items,
moreItems : moreItems
}

var app = myApp(config);

function MyApp(config) {
this.container = config.container;
this.items = config.items;
this.moreItems = config.moreItems;
this.current = 0;
}

MyApp.prototype.myUsefulFunction() {
this.moreItems[this.current].fadeIn();
}

Let's suppose I have a div#container filled with ul elements that have more than one li each. I'd like to access to the n-th li and fade the element in, but the console throws me back an error, stating fadeIn has no such method. Can you please help me sort it out?


Solution

  • jQuery returns a jquery object, which is a sort of array containing DOMELements.

    When you do: this.moreItems[this.current] you actually extract the DOMElement from the jquery array --> you have to turn it into a jquery object to be able to call fadeIn() !

    $(this.moreItems[this.current]).fadeIn();
    

    You can also use .eq(index) to filter the matched set to the only element corresponding to the index:

    this.moreItems.eq(this.current).fadeIn();
    

    DEMO


    Apart from that, the piece of code you show in your question has several syntax errors:

    1. To add a function to the prototype, you should do:

      MyApp.prototype.myUsefulFunction = function() {}
      

      and not MyApp.prototype.myUsefulFunction() {}

    2. Use the new operator to return a new instance of MyApp

      var app = new MyApp(config); // also spelling mistake: myApp != MyApp !!