lanqy
lanqy

Reputation: 3021

about jquery bind unbind

why this does't work? and how can I fixed it?

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
            $("button").unbind("click");
            $("div").show().fadeOut("slow",function(){
                $("button").bind("click");
            });
            })
        })
    </script>
    <style>
        div{width:600px;height:600px;display:none;background:red;}
    </style>
</head>
<body>
    <button>test</button>
    <div></div>
</body>
</html>

Upvotes: 2

Views: 704

Answers (1)

Nick Craver
Nick Craver

Reputation: 630429

You aren't specifying what to bind the click event to with $("button").bind("click"); (it doesn't make any assumptions there, it just silently binds nothing). You can do this with a named function you store though, for example:

$(document).ready(function() {
  function clickHandler() { 
    $("button").unbind("click");
    $("div").show().fadeOut("slow",function() {
      $("button").bind("click", clickHandler);
      //or: $("button").click(clickHandler);
    });
  }
  $("button").click(clickHandler);
});

You can test it out here. In your case though, it's easier to just check if the <div> is hidden, and don't un/re-bind anything, like this:

$(function() {
  $("button").click(function () { 
    $("div:hidden").show().fadeOut("slow");
  });
});

You can test that version here.

Upvotes: 5

Related Questions