I’m experimenting with using jQuery toggle to move between two functions. The results so far have been patchy. Below is the entire code of a trial scenario.
<html>
<head>
<script type="text/javascript" src="../js/jquery.js"></script>
<script>
$(document).ready(function(){
$('#id').on('click',function(event){
$(this).toggle(
function(){console.log('Hide');},
function(){console.log('Show');}
);
});
});
</script>
</head>
<body>
<div id="id">Hello</div>
</body>
</html>
So, when I click “Hello” for the first time, nothing appears in the log.
[Nothing]
On the second click, I get:
Hide
On the third, it adds:
Show
Hide
On the fourth, it adds:
Hide
Show
Hide
On the fifth, it adds:
Show
Hide
Show
Hide
I trust you can see the pattern 🙂 Why is it doing this? I’ve experimented with .stop(true) but to no avail.
Thanks.
toggle()is executed on click, so you don’t need theclickevent wrapper.Your current code attaches
toggle()to trigger on theclickevent the first time it is clicked, that is why you don’t get anything the first time you click the element.