Search code examples
jqueryclickbackground-colormouseentermouseleave

Creating navbar with jQuery: problems with background


I am having a problem with on() and off(). I created a navbar for which I want the div to be blue when you are with your mouse on top of it or when it is the last one clicked.

Therefore I used the mouseenter/ mouseleave (as I want the color to change gradually) and I used off() and on() as when the div is clicked (as the last one) is should not change with mouseenter/ mouseleave.

The problem is that with the code which I have below the mouseenter() mouseleave() events do not occur anymore when the div is clicked, can anyone help me with this? I used importance notation as well which does not work, and I really want to keep using jquery and the mouseenter/ mouseleave functionality. Thanks in advance!

$('.blok_nav').mouseenter(function(){
    $(this).animate(
        {backgroundColor: "blue", color: "red" }, { duration: 200, queue: false });
}   )

$('.blok_nav').mouseleave(function(){
    $(this).animate(
        {backgroundColor: "red", color: "blue" }, { duration: 200, queue: false });
}   )

$('.blok_nav').click(function(){
    $('blok_nav').not(this).on().css("background-color", "red").css("color", "blue")
        $(this).off('mouseenter').off('mouseleave').css("background-color", "green").css("color", "red")
})

Solution

  • You can use css transitions to achieve what you want and then apply a class when an element is clicked to highlight that element and remove the transitions

    CSS

    .block_nav {
      float:left;
      width:25%;
      text-align:center;
      vertical-align: middle;
    }
    
    .highlighted {
      color:white;
      background:green;
    }
    
    .blok_nav:not(.highlighted){
      color:blue;
      background-color:red ;
    }
    
    .blok_nav:not(.highlighted):hover {
      background-color: blue; 
      transition: background-color 500ms linear;
      color: red;
      transition: color 500ms linear; 
    }
    

    JQUERY

    $('.blok_nav').click(function() {
      $('.blok_nav').removeClass('highlighted');
      $(this).addClass('highlighted');
    });
    

    Refer fiddle

    Note: transition is not supported in earlier versions of IE