Create Simple Jquery Plugin To Add An Arrow On Active Menu

Sometime I need to put an arrow on active menu visited by website user or visitor on simple way as image below.

menu

Firstly, prepare HTML image for arrow and a list of menus

...
...
<img class="up_arrow" src="images/up_arrow.png" />
<div class="menu left">
    <a href="#" class="active">About Us</a>
    <a href="#">The Dream</a>
    <a href="#">Events</a>
    <a href="#">Contact Us</a>
    <a href="#">Affiliates</a>
</div>
...
...

set absolute and hide the image on CSS file for first load

.up_arrow {
    position: absolute;
    display: none;
}

add javascript and write it as jquery plugin

(function($) {
    $.fn.putMenuArrow = function() {
        $('.up_arrow').css({
            'display': 'block',
            'position': 'absolute',
            'left': ($(this).offset().left + $(this).outerWidth() / 2) - 17, // 17 is width of arrow image
            'top': $(this).offset().top - 19 //19 is height of arrow image
        });
    }
}(jQuery));


// call putMenuArrow plugin
$(document).ready(function() {
    $('.menu a.active').putMenuArrow();

    $('.menu a').click(function(e) {
        e.preventDefault();
        $('.menu a').removeClass('active');
        $(this).addClass('active');
        $(this).putMenuArrow();
    });
});

The complete demo can be found at:

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s