简体   繁体   中英

Retaining hover effect on click of menu item

I had created a navigation bar that has a .hover effect. but i want that effect that i have added to stay or add when i use .click and i also want to remove that effect when i click another bar. sorry for confusing :)

my code goes like this

html:

<div id="menubar">
    <div class="menubutton">Home</div>
    <div class="menubutton">Dessert</div>
    <div class="menubutton">About Us</div>
</div>

css:

#menubar {
    height: 30px;
    width: 100%;
    background-color: gray;
}

.menubutton {
    height: 30px;
    width: 60px;
    background-color: gray;
    display: inline-block;
    color: black;
    transition: background-color 0.5s ease;
}

.active {
    height: 30px;
    width: 60px;
    background-color: white;
    color: red;
}

jQuery:

$('.menubutton').hover(function() {
    $(this).addClass('active');
},
function() {
    $(this).removeClass('active');
});

Add a click Handler,

$('.menubutton').click(function() {
    $('.menubutton.active').removeClass('active')
    $(this).addClass('active');
});

Fiddle Demo

Create new class activeClick for click event as active class will remove on hover out event:-

$(function(){
 $('.menubutton').click(function(){    
   $('.menubutton').removeClass('activeClick');
   $(this).addClass('activeClick');
  });
});

Demo

Not tested, just wrote this here in the editor:

$(document).on('ready', function() {
    $('.menubutton').on('click', function() {
        $('.menubutton').removeClass('active clicked');
        $(this).addClass('active clicked')
    }).on('mouseenter', function() {
        $('.menubutton.active').not('.clicked').removeClass('active');
        $(this).addClass('active')
    }).on('mouseleave', function() {
        $(this).not('.clicked').removeClass('active')
    });
});

Try this :

$('.menubutton').click(function() {
    $('.menubutton').not(this).removeClass('active')
    $(this).toggleClass('active');
});

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM