Search code examples
jqueryclassfunctionmouseentermouseleave

jQuery document layout (multiple functions)


So I am a junior c# developer, and at the moment I am currently writing up a new website for myself. I am currently trying to make it so that I am able to have a class on say, an anchor tag called "default", then when you are to mouseenter() over the anchor, it will remove the class and then add the class of "hover".

Then when you mouseleave(), the "hover" class is then removed, and the "default" class is then appended again.

And then I will also have a click() call to remove "default" or "hover", to then append the class of "active"

I am having a bit of trouble with how to layout my .js document, it is quite a noobish question to ask really... But I am just not sure as to how I can write up a .js document, and have these multiple calls to different functions depending what is happening to the anchor element, all in the one document.

Any help is appreciated, cheers,
- Adam


Solution

  • To do this with jQuery:

    $('a.default').hover(
        function(){
            $(this).toggleClass('default hover');
        },
        function(){
            $(this).toggleClass('default hover');
        });
    

    JS Fiddle demo.

    Or you could use:

    $('a.default').hover(
        function(){
            $(this).removeClass('default').addClass('hover');
        },
        function(){
            $(this).removeClass('hover').addClass('default');
        });
    

    JS Fiddle demo.

    But, honestly, CSS would work just as well and be far more simple:

    a.default:link,
    a.default:visited {
        /* default styles */
    }
    
    a.default:hover,
    a.default:active {
        /* hovered styles */
    }
    

    JS Fiddle demo.

    References: