I have an asp.net panel with a style which hides it and I'm using JQuery to slideToggle the panel using a hyperlink. This works fine. However, if I add a button on the page that causes a postback the panel will default back to hidden. I understand why this is happening but what is the best way to keep the panels visibility state when a postback occurs?
<head runat="server">
<title></title>
<script type='text/javascript' src="jquery-1.4.1.min.js">
</script>
<style type="text/css">
.panel
{
display: none;
}
</style>
<script type="text/javascript">
$(function() {
$("#Link1").click(function(evt) {
evt.preventDefault();
$('#panelText').slideToggle('slow');
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:HyperLink ID="Link1" runat="server" NavigateUrl="#">SlideToggle
</asp:HyperLink><br />
<asp:Panel ID="panelText" runat="server" CssClass="panel">
Some text</asp:Panel>
<asp:Button ID="button1" runat="server" Text="Postback" />
</form>
</body>
</html>
Here's how I solved my problem...
<head runat="server">
<title></title>
<script type='text/javascript' src="jquery-1.4.1.min.js">
</script>
<style type="text/css">
.panel
{
display: none;
}
</style>
<script type="text/javascript">
$(function() {
$("#Link1").click(function(evt) {
evt.preventDefault();
$('#panelText').slideToggle('slow');
if ($('#panelText').hasClass('panel')) {
$('#PanelState').attr('value', 'true');
} else {
$('#PanelState').attr('value', 'false');
}
});
});
$(document).ready(function() {
if ($('#PanelState').attr('value') == 'false') {
$('#panelText').addClass('panel');
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:HiddenField ID="PanelState" runat="server" Value="false" />
<asp:HyperLink ID="Link1" runat="server" NavigateUrl="#">SlideToggle
</asp:HyperLink><br />
<asp:Panel ID="panelText" runat="server">
Some text</asp:Panel>
<asp:Button ID="button1" runat="server" Text="Postback" />
</form>
</body>
</html>
Add a hidden field in form:
<asp:HiddenField id="hdnPanelState" runat="Server" value="false" />
and modify the JS function:
<script type="text/javascript">
$(function() {
$("#Link1").click(function(evt) {
evt.preventDefault();
$('#panelText').slideToggle('slow');
//YOU WILL ALSO NEED TO CALCULATE IF SHOWING PANEL OR HIDING
$("#hdnPanelState").attr("value","true");//Store Value
});
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With