Hai Truong IT
Hai Truong IT

Reputation: 4187

Error when converting from jquery to mootools?

I have some code that uses jquery:

$(document).ready(function(){
   $('#tabs div').hide();
   $('#tabs div:first').show();
   $('#tabs ul li:first').addClass('active');
   $('#tabs ul li a').click(function(){ 
      $('#tabs ul li').removeClass('active');
      $(this).parent().addClass('active'); 
      var currentTab = $(this).attr('href'); 
      $('#tabs div').hide();
      $(currentTab).show();
      return false;
   });
});

And I converted it to use mootools

window.addEvent('domready', function() {
    $$('#tabs div').hide();
    $$('#tabs div:first').show();
    $$('#tabs ul li:first').addClass('active');
    $$('#tabs ul li a').addEvent('click', function(event) {
        $$('#tabs ul li').removeClass('active');
        $$(this).parent().addClass('active'); 
        var currentTab = $(this).attr('href'); 
        $$('#tabs div').hide();
        $$(currentTab).show();
        return false;

    });
});

But I get an error: $$(this).parent is not a function

How do I fix it?

Upvotes: 0

Views: 118

Answers (2)

island205
island205

Reputation: 1740

there is no parent method in mootools, instead, the method name is getParent.it is not difficulty to convert from jquery to mootools. it is helpful having a look on docs.

Upvotes: 0

Dimitar Christoff
Dimitar Christoff

Reputation: 26165

this is quite poor. many bad practices and api differences.

window.addEvent('domready', function() {
    // cache what we will reuse into vars
    var tabs = document.id('tabs'), 
        divs = tabs.getElements('div'),
        // for loop
        len = divs.length,
        ii = 1;

    // hide all but the first one w/o extra lookups.
    for (;ii < len;++ii)
        divs[ii].hide();

    // first match
    tabs.getElement('ul li').addClass('active');

    // attach the events to all links
    tabs.getElements('ul li a').addEvent('click', function(event) {
        event && event.stop();

        tabs.getElement('ul li').removeClass('active');
        this.getParent().addClass('active'); 
        tabs.getElement(this.get('href')).show();
        return false;
    });
});

basically, a few practices you need to consider:

  • cache your selectors, esp repetitive stuff
  • avoid going to dom and work from memory
  • use normal js array looping or methods to avoid an extra selector like :first or :last, you already have the data
  • stop the event directly, don't return false
  • .getElement() will return the first match
  • avoid storing stuff into variables that you won't reuse
  • consider using event delegation and attaching a click handler once to the ul rather than to all child A's - eg, tabs.getElement('ul').addEvent('click:relay(li a)', fn) will achieve the same but only create a single event handler

Upvotes: 2

Related Questions