| 2 min read
Being a web developer, everyone find JQuery a life savior. For the past two months, I am working on some heavy JavaScript work. Thanks to JQuery for helping me a lot with unbelievably simple to use api. But there are some situations where you will have to depend on your own code instead of using 'the beautiful JQuery library'.
I was struggling with some responsive menu bar stuff. We had to make it responsive in a very creative manner (not like bootstrap responsive navigation bar). There I needed to iterate each element of list in reverse manner. As usual, I googled for any ready api available in JQuery but unfortunately there was not any good and short method available. I could have easily achieved reverse iteration using
for( i = $('li').size(); i>= 0 ; i--){ | |
$('li').eq(i).someSuperLogicHere; | |
} |
But somehow this was not the best possible solution to iterate and add logic. After looking for appropriate solution online, I stumbled upon this archive : http://www.mail-archive.com/discuss@jquery.com/msg04261.html which guided me to get it done by creating one line plugin for JQuery.
Yes, there is no .reverse() i.e. reverse iteration in JQuery. What if we don't have. We can create our own plugin. No worries, it is not lengthy. Just a one liner, I promise. Just add this in your Js file.
jQuery.fn.reverse = [].reverse;
Well, that's it.
Anyone with moderate JQuery and JavaScript knowledge can explain working of the above prototype. It takes elements in to array and reverse it using JavaScript reverse.
Usage is simple, if you are using .each iterator just add .reverse() before .each iterator function.
$('li').reverse().each( function() { | |
// YOUR SUPER LOGIC HER | |
} ); |
Simple, isn't it?