Jay Corbett
Jay Corbett

Reputation: 28391

jQuery Toggle function doesn't work on 1st click

I realized the solution to this problem while I was creating the documentation to ASK this question...so I am posting the answer if for no other reason than to keep me from wasting time on this in the future

Upvotes: 4

Views: 7669

Answers (3)

thvs86
thvs86

Reputation: 1528

I know this is a really old question, but just for people that are looking for a quick fix this worked for me:

a. in the PHP/HTML file:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/.../jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#pClick").click(function(){          
            $("#pText").toggle();
            $("#pText").text("...");
        });
    });
    </script>

b. in the CSS file:

#pText {display: none;}

It now works even on the first click. It's a simple, quick answer that I hope will be useful.

Upvotes: 0

Owen
Owen

Reputation: 84493

toggle() is pretty buggy at times, i've had it do odd things to checkmarks (unchecking them) and other assorted issues. i'd suggest just handling it using a click event, much less minor annoyances. and this way, you don't have to worry about what state #lowerDiv is in in the first place:

$('#upperDiv').click(function() {
    $('#lowerDiv').animate({
        'opacity' : 'toggle',
    });
});

Upvotes: 2

Jay Corbett
Jay Corbett

Reputation: 28391

If the content to be TOGGLEd is displayed (visible) when the page is rendered the functions would be in the following order, if the content is hidden originally then reverse the functions

<html>
<head>
<style>
 #upperDiv {width:200px; height:20px; text-align:center; cursor:pointer; }
 #lowerDiv {width:200px; height:20px; background-color:red; border:#206ba4 1px solid;}
</style>

<script language="Javascript" src="javascript/jquery-1.2.6.min.js"></script>
<script type="text/JavaScript">

$(function(){
$('#upperDiv').toggle (
    function(){ 
        $("#lowerDiv").hide() ; 
        },
    function(){ 
        $("#lowerDiv").show() ; 
        }
); // End toggle
 }); // End eventlistener

</script>
</head>
<body>
<div id="upperDiv" >Upper div</div>
<div id="lowerDiv" >Lover Div</div>
</body>
</html>

Upvotes: 4

Related Questions