Thursday, 10 February 2011

JQuery Hover Effect on Current, Previous and Next elements

I created this simple effect with JQuery and a little bit of CSS. What is does is if you move your mouse cursor over a link it calls the .hover() function and then it applies a class style using .addClass() to the element you hovered over with the mouse and in addition to this is applies a style to its adjacent neighbours using .next() and .prev() to select the links to which to apply the style.
 

The code is really simple. First off, you use a hover function. The first argument you pass to it is what to do when the mouse hovers over the element. I use .addClass() to apply a style to the element being hovered over ($(this)). The next argument to pass to the function is what to do when the mouse moves off the element and I use .removeClass() to reset the style of the element back to how it was. I encapsulate the arguments in anonymous functions.

In order to access the elements adjacent to that being selected you can use the .next() and .prev() functions, so if, for example, I had a list of 3 items and was hovering over the second one, I can use prev() to have access to the first element and next() to access the third element. When I move the mouse to highlight the first element, there is no previous element so it doesn't select anything to the left but the next element is still there and is accessible. If I highlight the third element then there is no next element so it only has the previous element to select.


Anyway, here's the javascript code:

$(document).ready(function(){
    $('a.link').hover(
        /*Carry this out when the mouse hovers over the element*/
        function(){
             $(this).addClass('bigger');
             $(this).next().addClass('big');
             $(this).prev().addClass('big');
        },
        /*Carry this out when the mouse moves off the element*/ 
        function(){
             $(this).removeClass('bigger');
             $(this).next().removeClass('big');
             $(this).prev().removeClass('big');
        }
    )
});

Now, the CSS to align the elements when the font size got bigger was not straightforward. One would assume that you need to use a combination of vertical-align:middle and display:table-cell or display:inline-block but these didn't do what I wanted. In the end I found the best way to solve the problem was to give the container element (div) a height and then use a large line-height, a large margin-top and text-align:bottom to allow the text to get bigger and not interfere with the content above or below it:

div {height:1.2in; width:100%; border:1px solid black;}
a {margin-top:50px; vertical-align:bottom; line-height:100px; text-decoration:none;}

You can download the code here: http://www.mediafire.com/?kydzwwl4bb4ogjk

And it's under the public domain license so you're free to do what you like with it.

1 comment: