Monday, March 2, 2015

Hide and Show div using Jquery

We have a requirement to hide and show our Grid in a div. 

Following is the code to achieve this functionality

Define the first div which shows the caption Show/Hide. Whenever the mouse is over the div "divtoggle1" second div "divOrders" is either shown or hidden

The below <Div> is defined with caption Show/Hide

 <div id="divtoggle1" style="text-align:left;width:250px">
                 Show/Hide
  </div>

The below <Div> contains the GridView which we need to Show/Hide

<div id="divOrders">
 
<asp:GridView ID="grvOrders" runat="server" AutoGenerateColumns="False" >

     <Columns>
          <asp:TemplateField HeaderText="firstcolumn" >
                      <ItemTemplate>
                              <asp:LinkButton ID="lnkName" runat="server" Text='<%#
                                  DataBinder.Eval(Container.DataItem,"Names") %>'                                                                               CommandName="OrderDetail">
                            </asp:LinkButton>
                        </ItemTemplate>
            </asp:TemplateField>
        </Columns>
  </asp:GridView>
</div>  

The Jquery part which toggle the div

we are access the div "divtoggle" with "#" sign because in Jquery when you want to access any element by ID you have to use "#" sign before the name of element.

we call the "divtoggle1" mouseover event and in that event we are checking the second div "divOrders".

 if "#divOrders" visible then hide it or if it is hidden then make it visible. we also added delay function to make the Show/Hide smooth and we used hide argument "slow".

<script type="text/javascript">
    $(document).ready(function () {
        $("#divtoggle1").mouseover(function () {

            if ($('#divOrders').is(':visible')) {
                $("#divOrders").delay(100).hide('slow');
                $("#divtoggle1").text('Show Orders');
            }
            else {
                $("#divOrders").delay(100).show('slow');
                $("#divtoggle1").text('Hide Orders');
            }

        }); // end of mouse over
    });    // end of ready function
 

</script>