JQuery Plugin odd and even element

From CoderLearner
Jump to: navigation, search

Description

Write a plugin to display different color for odd or even element.

Syntax

jQuery.fn.showEvenOdd = function(options) {

                    var defaults = {
                        odd: 'blue',
                        even: 'green'
                    };

                    var settings = $.extend(defaults, options);

                    return this.each(function(index) {
                        if (index % 2 === 0) {
                            $(this).css('color', settings.odd);
                        }

                        else {
                            $(this).css('color', settings.even);
                        }
                    });
                };

Example 1

<!DOCTYPE html>
<html>
    <head>
        <title>jquery plugin</title>
        <script 
            type="text/javascript" 
            src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
        </script>
        <script>
            $().ready(function() {
                jQuery.fn.showEvenOdd = function(options) {

                    var defaults = {
                        odd: 'blue',
                        even: 'green'
                    };

                    var settings = $.extend(defaults, options);
// check for the index of the element for odd or even
                    return this.each(function(index) {
                        if (index % 2 === 0) {
                            $(this).css('color', settings.odd);
                        }

                        else {
                            $(this).css('color', settings.even);
                        }
                    });
                };
                
                $('a').showEvenOdd();
                $('ul li').showEvenOdd();
            });
        </script>
    </head>
    <body>
        <a href="coderlearner" title="learn simple jquery plugin">jQuery</a> <br/>
        <a href="google.com" title="search google">Google</a> <br/>
        <a href="yahoo.com" title="search yahoo">Yahoo</a> <br/>
        <a href="bing.com" title="search bing">Bing</a> <br/>

        <ul>
            <li>God</li>
            <li>Heaven</li>
            <li>Ghost</li>
            <li>Gift</li>
        </ul>
    </body>
</html>

Result

JQuery Plugin odd and even element.png

Usage

  • With parameter.
$('ul li').showEvenOdd({
                    'odd': 'yellow',
                    'even': 'black'

                });