How to fire a function before and after automatically in a jquery plugin?

Why is this jQuery plugin for adding commas in numbers lagging my webpage?

  • $.fn.digits = function(){     return this.each(function(){         $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );     }) } Call it like this: $("#total").digits(); I think it lags because of me having a couple hundred of these: $("#total").digits(); Is there a way to get rid of that lag?

  • Answer:

    Manipulations of the DOM, i.e. modifying the text of elements, moving elements, etc. is slow. Especially if you hundreds of them like you said. Also the fact that you are using replace, i.e. regex, means it has to match every single total. You could have as easy just to string manipulations which would have been more efficient.

Andrey Kulakevich at Quora Visit the source

Was this solution helpful to you?

Other answers

It would be much better to do that text manipulation on the server-side. Javascript should really only be used to perform tasks that cannot be accomplished server-side. That being said, I don't think your script is hugely problematic, unless it ran multiple times. I run it here (http://jsfiddle.net/A34Zx/) on 2000 numbers, and it only takes a split second. How often is your digits function being called?

Marty Naselli

Because you do massive DOM manipulation in your GUI thread. Will always cause lag. Why can't you just use number.toFixed()?

Thomas Symalla

function commaSeparateNumber(val){     while (/(\d+)(\d{3})/.test(val.toString())){       val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');     }     return val;   } use it like this commaSeparateNumber("1234567") ;

Nikita Somaiya

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.