There are many posts on this topic already but none that address my issue directly. Here is my current setup:
I have a div with the ID #ptwesv
;
and another div containing the content I want to show hide with the ID #ptwest
.
The jQuery I'm using is this:
<script>
jQuery("#ptwesv").click(function(){
jQuery("#ptwest").show();
});
jQuery("#ptwesv").click(function(){
jQuery("#ptwest").hide();
});
</script>
This is hiding the #ptwest
container correctly on click, but then doesn't show the conatiner when I click the trigger element (#ptwesv
) again. I presume this is because once the element has been hidden, clicking on the trigger again is causing the actions to work against each other.
I'm using this W3 exmaple as a reference, the only salient different I notice is that there are different trigger elements for show/hide.
Is it possible to trigger show/hide of an element from the a single div and how can I get this to work?
There are many posts on this topic already but none that address my issue directly. Here is my current setup:
I have a div with the ID #ptwesv
;
and another div containing the content I want to show hide with the ID #ptwest
.
The jQuery I'm using is this:
<script>
jQuery("#ptwesv").click(function(){
jQuery("#ptwest").show();
});
jQuery("#ptwesv").click(function(){
jQuery("#ptwest").hide();
});
</script>
This is hiding the #ptwest
container correctly on click, but then doesn't show the conatiner when I click the trigger element (#ptwesv
) again. I presume this is because once the element has been hidden, clicking on the trigger again is causing the actions to work against each other.
I'm using this W3 exmaple as a reference, the only salient different I notice is that there are different trigger elements for show/hide.
Is it possible to trigger show/hide of an element from the a single div and how can I get this to work?
Share Improve this question asked Jul 10, 2017 at 15:20 user5887886user5887886 2-
1
jQuery("#ptwest").toggle()
– tymeJV Commented Jul 10, 2017 at 15:22 - You're overwriting your first click event when you're setting the second. All given answers so far would work. – vi5ion Commented Jul 10, 2017 at 15:26
3 Answers
Reset to default 4jQuery("#ptwesv").click(function(){
jQuery("#ptwest").toggle();
});
is the way you want. It toggles the element. So if it is shown it hides and the other way around.
At the moment the element will always hide, because of twice the same click element.
Because Id
is unique for whole document. try with toggle()
jQuery("#ptwesv").click(function(){
jQuery("#ptwest").toggle();
});
The toggle() method toggles between hide() and show() for the selected elements.
This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.
$("#ptwesv").click(function(){
$("#ptwest").toggle();
});