Jelle Spekken
Jelle Spekken

Reputation:

How do I create methods for an HTML element?

I'm trying to create a simple, small and basic javascript framework just for learning purposes. But the thing is that i'm allready stuck at the very basics.

I'm trying to do something like this:

$('testdiv').testFunction();

And the code i've written for that:

var elementID;
var smallFramework = {

  $:function(id) {
    this.elementID = id;
  },

  testFunction:function() {
    alert(this.elementID);
  }

};
window.$ = smallFramework.$;

But in return I get:

$('testdiv) is undefined

Can anyone help me with this small and hopefully easy question?

Upvotes: 2

Views: 284

Answers (3)

Breton
Breton

Reputation: 15582

Try

smallFramework.$('testdiv'); 

instead. According to the code you posted, that's where your $ function ended up.

Or alternatively, it looks like you're trying to replicate something like jQuery. You might want to try something like this.

var $ = smallFramework = (function () {
   var f = 
   {

     find:function(id) {
       f.elementID = id;
       return f;  //every function should return f, for chaining to work
     },

     testFunction:function() {
       alert(f.elementID);
       return f;
     }

   }

return f.find  //the find function will be assigned to $. 
//and also assigned to smallFramework.
//the find function returns f, so you get access to testFunction via chaining
// like $("blah").testFunction()

})() //note this function gets called immediately.

this code may look confusing to someone new to JavaScript because it depends heavily on the concept of closures. I suggest that if this doesn't make sense, spend some time at Douglas Crockford's JavaScript website. This is important because the code above will bite if you happen to use this in the find function because this won't be bound to f, as you may expect it to be when you use it from $ or smallFramework.

Upvotes: 1

meouw
meouw

Reputation: 42140

If you're trying to add methods to an HTML element you could do something along these lines.

$ = function( elementId ) {
    var element = document.getElementById( elementId );
    element.testFunction = function(){
        alert( this.id );
        return this; // for chaining
    }
    return element;
}

$('test').testFunction();

Upvotes: 1

Shog9
Shog9

Reputation: 159668

To get the behavior you're expecting, you need the $ function to return an object with a method named testFunction. Try:

var smallFramework = // an object for namespacing
{
  $:function(id) // the core function - returns an object wrapping the id
  {
    return {                    // return an object literal
      elementID: id,            // holding the id passed in
      testFunction: function()  // and a simple method
      {
         alert(this.elementID);
      }
    };
  }
};

Of course, there are many other ways to achieve the behavior you desire.

Upvotes: 2

Related Questions