Search code examples
jqueryjquery-on

JQuery on with multiple events for mutiple elements


No doubt it works but i know it's not a good code.So i want to accomplish

  • Make it work using one on()

    <script>
        $(document).on("mouseenter", ".BUTTON_ONE", function() {
            $(this).animate({ 
                \'padding-right\' : 10,
            },30);
        });
        $(document).on("mouseleave", ".BUTTON_ONE", function() {
            $(this).animate({ 
                \'padding-right\' : 4,
            },30);
        });
        $(document).on("mouseenter", ".BUTTON_TWO", function() {
            $(this).animate({ 
                \'padding-left\' : 10,
            },30);
        });
        $(document).on("mouseleave", ".BUTTON_TWO", function() {
            $(this).animate({ 
                \'padding-left\' : 4,
            },30);
        });
        $(document).on("mouseenter", ".BUTTON_THREE", function() {
            $(this).animate({ 
                \'padding-left\' : 10,
            },30);
        });
        $(document).on("mouseleave", ".BUTTON_THREE", function() {
            $(this).animate({ 
                \'padding-left\' : 4,
            },30);
        });
     </script>
    

Solution

  • Maybe like this: :)

    $(document).ready(function() {
        $(document.body)
        .on({
            'mouseenter': function(e) { animate_padding_right(e,10); },
            'mouseleave': function(e) { animate_padding_right(e,4); }
        }, ".BUTTON_ONE")
        .on({
            'mouseenter': function(e) { animate_padding_left(e,10); },
            'mouseleave': function(e) { animate_padding_left(e,4); }
        }, ".BUTTON_TWO,.BUTTON_THREE");
    });
    function animate_padding_left(e,val) {
        $(e.target).animate({'padding-left':val},30);
    }
    function animate_padding_right(e,val) {
        $(e.target).animate({'padding-right':val},30);
    }
    

    Notice that I use $(document.body) because it's faster & more effective for this case.

    Working fiddle: http://www.codeply.com/go/uUoOo1vlaB