LogicButAllLang
LogicButAllLang

Reputation: 15

Two jquery functions work on click, but together

So when I click once it does both the Jquery codes ... I would like it that when I click it slides down and stays down until I click again, how to?

I tried click1 and click2 but it is not ideal. I also tried giving them other id but it wasn't logical.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script> 
$(document).ready(function(){
    $("#flip").click(function(){
        $("#panel").slideDown(1500);
    });
});
</script>

<script> 
$(document).ready(function(){
    $("#flip").click(function(){
        $("#panel").slideUp(1500);
    });
});
</script>


<style> 
#panel, #flip {
    padding: 5px;
    text-align: center;
    background-color: #e5eecc;
    border: solid 1px #c3c3c3;
}

#panel {
    padding: 50px;
    display: none;
}
</style>
</head>
<body>

<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>

</body>
</html>

Upvotes: 1

Views: 52

Answers (3)

Michael Sacket
Michael Sacket

Reputation: 907

The issue is that there are two click events bound to the div. Instead, you need to keep track of the state (i.e. isUp or isDown) and do it with a single click handler. Something like this:

$(document).ready(function(){
    var isDown = false;
    $("#flip").click(function(){
        if( !isDown ){
            $("#panel").slideDown(1500);
            isDown = true;
        } else {
            $("#panel").slideUp(1500);
            isDown = false;
        }
    });
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337627

As you've seen, when you attach multiple handlers they all execute at the same time. Instead, attach one handler and call slideToggle() instead.

Also note that you may want to add a call to stop() in there so that when the element is clicked rapidly the animations do not queue up. Try this:

$(document).ready(function() {
  $("#flip").click(function() {
    $("#panel").stop(true).slideToggle(1500);
  });
});
#panel,
#flip {
  padding: 5px;
  text-align: center;
  background-color: #e5eecc;
  border: solid 1px #c3c3c3;
}
#panel {
  padding: 50px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>

Upvotes: 2

Flash Thunder
Flash Thunder

Reputation: 12045

$(document).ready(function(){
    $("#flip").click(function(){
       if($('#panel').is(':visible')){
           $("#panel").slideUp(1500);
       }else{
           $("#panel").slideDown(1500);
       }
    });
});

Upvotes: 0

Related Questions