views:

15

answers:

2

Hi Guys,

I must be missing something fundamental, but for the life of me cant work it out.

the idea is when u click that click event is then unbind. Also to note the alert('test') is not firing.

  $(document).ready(function() {
  $('#menu .cat-item a').each( function() {
    $(this).bind('click',hide).unbind('click',hide);
  });
 });


 function hide(){
   alert('test')
    $("#home-content").fadeIn();
   $("#home-page").fadeOut();
 } 

Using jquery 1.4

Many Thanks

Dan

A: 

You are unbinding immediately after you bind! You'll need to unbind within the handler (hide) to ensure that it's executed, otherwise you might consider this instead:

$(document).ready(function() {
    $('#menu .cat-item a').one("click", hide);
});

one will ensure that a handler is only executed once per element.

karim79
Thats a good one to remember,thanks
Dan
A: 

Since jQuery supports a fluent programming style bind actually returns the this object.

So in this case you are first adding the handler and then immediately removing it.

The correct version is

$(document).ready(function() {
    $('#menu .cat-item a').each( function() {
         $(this).bind('click',hide);
    });
});


function hide(){
    $(this).unbind('click',hide);
    $("#home-content").fadeIn();
    $("#home-page").fadeOut();
} 
Sean Kinsey
yep thats the one. Many Thanks
Dan