Mootools to jQuery

Basically I suck at javascript and i found a mootools code snippet while on another copy and paste quest and i use jquery so, yea, can anyone help me convert the code?

Thanks :slight_smile:

window.addEvent('domready', function() {
  $$('img.captioned').each(function(el) {
    var captionText = ( el.getProperty('title')!=null )
                    ? el.getProperty('title') : el.getProperty('alt');
    if ( captionText!=null ) {
      var figure = new Element('div', {
        'class' : 'figure',
        'styles' : {
          'width' : el.get('width').toInt() + 10
        }
      });
      var caption = new Element('p', {
        'class' : 'caption',
        'html' : captionText
      });
      figure.wraps(el);
      caption.inject(el,'after');
    } else {
      alert('The image: "'+el.getProperty('src')+'" needs a title or alt value.');
    }
  });
});

@ http://sixrevisions.com/tutorials/mootools-tutorials/how-to-auto-caption-images-using-mootools/

the problem is im not even a basic javascript coder and im not familiar with jquery

How about this then - I’ll do some obvious conversion stuff, and you can test it and let us know where any problems occur.

So that you can tell the difference, I’ll use a code block for the original code, and a javascript code block for the jQuery-related code.

First we have the part that is waiting for the page to be ready,


window.addEvent('domready', function() {
    ...
});

which in jQuery is done with a jQuery callback:


$(function () {
    ...
});

Next we get some elements and apply a function to each matching element

$$('img.captioned').each(function(el) {
    ...
});

In jQuery the single dollar sign is used for selectors, and the [url=“http://api.jquery.com/each/”]each function uses the first parameter for an index, and the second one for the element.

However, a more appropriate way in jQuery to access each element is via the this keyword from within the function, so no function arguments are necessary at all.

We also state the variables we’ll be creating with in the first function line.


$('img.captioned').each(function () {
    var figure, caption;
    ...
});

Here we get the caption text and check if it’s valid


var captionText = ( el.getProperty('title')!=null )
            ? el.getProperty('title') : el.getProperty('alt');
if ( captionText!=null ) {

which we can do much more easily with regular normal JavaScript. I won’t assign a value for it now, because it’s used only once later on.


if (this.title || this.alt) {

Next, we create a div with content


var figure = new Element('div', {
    'class' : 'figure',
    'styles' : {
        'width' : el.get('width').toInt() + 10
    }
});

which can in jQuery be done by passing HTML to the jQuery object, followed by a similar attribute list, except that we use the css object on the figure to specify css styles.

As jQuery is primarily for working with the DOM, there are no in-built integer handling functions so we’ll do that using standard JavaScript.


figure = $('<div></div>', {
    'class' : 'figure'
});
$(figure).css('width', Math.floor($(this).width() + 10));

This is creating a paragraph, and embedding the caption as html content.


var caption = new Element('p', {
    'class' : 'caption',
    'html' : captionText
});

jQuery uses a method called

(http://api.jquery.com/html/#html2) to add html content to an element:


```javascript

caption = $('&lt;p&gt;&lt;/p&gt;', {
    'class' : 'caption'
})
.html(this.title || this.alt);

Here we wrap the div around the element, and after the element we put the caption.


figure.wraps(el);
caption.inject(el,'after');

jQuery has a wide range of manipulation techniques, so from our grab-bag we’ll pick the [url=“http://api.jquery.com/wrap/”]wrap method and the [url=“http://api.jquery.com/after/”]after method here, so that the element being worked on can remain the primary focus:

First we wrap the element (referenced by the this keyword) with figure, and then after the element we put the caption.


this.wrap(figure).after(caption);

Finally, we alert something if things go wrong.


} else {
    alert('The image: "'+el.getProperty('src')+'" needs a title or alt value.');
}

for which we don’t need anything more extreme than normal JavaScript.


} else {
    alert('The image: "' + this.src + '" needs a title or alt value.');
}

Here’s what you end up with as a whole, when it’s all put together:


$(function () {
    $('img.captioned').each(function () {
        var figure, caption;
        if (this.title || this.alt) {
            figure = $('&lt;div&gt;&lt;/div&gt;', {
                'class': 'figure'
            });
            $(figure).css('width', Math.floor($(this).width() + 10));
            caption = $('&lt;p&gt;&lt;/p&gt;', {
                'class' : 'caption'
            })
            .html(this.title || this.alt);
            $(this).wrap(figure).after(caption);
        } else {
            alert('The image: "' + this.src + '" needs a title or alt value.');
        }
    });
});

And if you want to do it using more of a chained approach, as the variables are used only once, you can move the assignments of those variables instead to where they will be used.


$(function () {
    $('img.captioned').each(function () {
        if (this.title || this.alt) {
            $(this).wrap(
                $($('&lt;div&gt;&lt;/div&gt;', {
                    'class': 'figure'
                }))
                .css('width', Math.floor($(this).width() + 10)))
            .after(
                $('&lt;p&gt;&lt;/p&gt;', {
                    'class' : 'caption'
                })
                .html(this.title || this.alt)
            );
        } else {
            alert('The image: "' + this.src + '" needs a title or alt value.');
        }
    });
});

Why don’t you try to convert it to jQuery first and then we’ll help you fill in the gaps. That way you’ll learn something.