0

I have the following code for a button in my nav menu:

div onmouseover=\"changeBGColor(this,'#b90707');changeColor(this,'#fff');\" onmouseout=\"changeBGColor(this,'');changeColor(this,'#333');\" onClick="" class='navbtn'>Entry /div

And the following code to keep the element active:

  $('.navbtn').each(function(){
    var path = window.location.href;
    var current = path.substring(path.lastIndexOf('/')+1);
    var url = $(this).attr('onClick').substring(path.lastIndexOf('/')+18,$(this).attr('onClick').length-1);

    if(url == current ){
        changeBGColor(this,'#b90707');changeColor(this,'#fff');
        $(this).onmouseout = '';
        $(this).onmouseover= '';
    };
});       

The element remains active until i move the mouse over the element. I would like to remain active anytime no matter where i move my mouse on..

Emil Dumbazu
  • 642
  • 4
  • 22
  • 35
  • Why do you set an `mouseout`-event at all if you don't need it? And please don't use inline handler in the elements attributes. It makes the code much harder to maintain. – feeela Oct 13 '12 at 12:35

1 Answers1

0

That code appears to be changing the background color in the onmouseout handler. If this reverts the color to what it was, try not handling that event to see if it stays the same.

Edit: Setting the handler to the empty string doesn't look right. See Best way to remove an event handler in jQuery?

Edit:

Something like this might be better:

$(this).unbind('mouseleave'); 

Or (according to the above link, this is the preferred approach):

$(this).off('mouseleave'); 

Edit:

For this to work you will need to remove the inline handlers you have set up for onmouseover and onmouseout. The reason for this is that $(this).off('mouseleave'); won't work unless the events are wired up with jQuery, and $(this).onmouseover= ''; won't work either for the same reason.

You will then need to wire up the event handlers with some jQuery:

$('.navbtn').mouseover(function () {
    changeBGColor(this,'#b90707'); 
});

$('.navbtn').mouseout(function () {
    changeBGColor(this, '');
});

Now where you are currently doing:

if(url == current ){ 
    changeBGColor(this,'#b90707');changeColor(this,'#fff'); 
    $(this).onmouseout = ''; 
    $(this).onmouseover= ''; 
}; 

You can instead do:

if(url == current ){ 
    changeBGColor(this,'#b90707');changeColor(this,'#fff'); 
    $('.navbtn').off('mouseout');
    $('.navbtn').off('mouseover'); 
}; 

Which should ensure that the colors you have just set stay that way.

Note that jQuery 1.7+ is required for the off syntax to work.

Community
  • 1
  • 1
nick_w
  • 13,990
  • 2
  • 47
  • 67
  • Could you explain in more detail what didn't work? The example I posted worked fine for me. – nick_w Oct 13 '12 at 23:19
  • @EmilDumbazu it would also be useful if you could edit your question with the code that you have tried but doesn't work. – nick_w Oct 13 '12 at 23:28