Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a callback function to the addClass method of jQuery?

I'm using Prettify from Google and Markdown and I want each time I find a pre code added in the markdown textarea to call again the prettyPrint() function.

This is my actual code:

if($('#wmd-preview').length > 0) {
  $('#wmd-preview').on('DOMNodeInserted DOMNodeRemoved',function(){
    $(this).find("pre").not('.prettyprint').addClass("prettyprint");
  });
}

But I want something like:

$(this).find("pre").not('.prettyprint').addClass("prettyprint",function(){
  prettyPrint();
});

Is there any possible way to achieve this?

like image 200
Mihai Matei Avatar asked Jan 28 '13 17:01

Mihai Matei


People also ask

How addClass in jQuery?

Syntax: $(selector). addClass(className); Parameters: It accepts a parameter “className”, the name of the new class that is to be added.

How to add class to div using jQuery?

jQuery addClass() Method The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

What is callback method in jQuery?

jQuery Callback Functions JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors. To prevent this, you can create a callback function. A callback function is executed after the current effect is finished.


2 Answers

You could extend .addClass() jquery's method to let it accept a callback function:

;(function ($) {
    var oAddClass = $.fn.addClass;
    $.fn.addClass = function () {
        for (var i in arguments) {
            var arg = arguments[i];
            if ( !! (arg && arg.constructor && arg.call && arg.apply)) {
                setTimeout(arg.bind(this));
                delete arguments[i];
            }
        }
        return oAddClass.apply(this, arguments);
    }

})(jQuery);

Then use it as usual:

 $('pre:not(.prettyprint)').addClass('prettyprint',prettyPrint);
like image 124
A. Wolff Avatar answered Oct 28 '22 12:10

A. Wolff


As far as I understand, you need this:

$(this).find("pre").not('.prettyprint').each(function(){
   $(this).addClass("prettyprint");
   prettyPrint();
})
like image 30
Viktor S. Avatar answered Oct 28 '22 12:10

Viktor S.