Werner Bisschoff
Werner Bisschoff

Reputation: 177

JavaScript Library needed for Showing/Hiding a div panel using JQuery

I have a simple fieldset and div panel, which I want to initially show. If you then click on a button/image or text I then want to hide the div panel. Let's call this "myPanel". Clicking on the button/image or text once more will then show it again. Now I have a solution in JavaScript below, but my question is how can I create a library for this and re-use this instead of writing out the method's for multiple panels. Something similar to this:

var panel = new library.panel("myPanel");

Then all events will be handled and variables defined in the JavaScript library.

Consider the following code:

    <fieldset>
        <legend>My Panel<a id="MyPanelExpandCollapseButton" class="pull-right" href="javascript:void(0);">[-]</a></legend>
        <div id="MyPanel">
                Panel Contents goes here
        </div>
    </fieldset>
    <script type="text/javascript">
        //This should be inside the JavaScript Library
        var myPanelShown = true;
        $(document).ready(function () {
            $('#MyPanelExpandCollapseButton').click(showHideMyPanel);
            if (myPanelShown) {
                $('#MyPanel').show();
            } else {
                $('#MyPanel').hide();
            }
        });

        function showHideMyPanel() {
            if (myPanelShown) {
                $('#MyPanelExpandCollapseButton').text("[+]");
                $('#MyPanel').slideUp();
                myPanelShown = false;
            } else {
                $('#MyPanelExpandCollapseButton').text("[-]");
                $('#MyPanel').slideDown();
                myPanelShown = true;
            }
        }
    </script>

Upvotes: 0

Views: 139

Answers (2)

Hemant
Hemant

Reputation: 1018

If you want to make it yours then it is simple, make a function in separate js file :

   function showHideBlock(panelId, buttonId){
     if($(panelId).css('display') == 'none'){
       $(panelId).slideDown('normal');
       $(buttonId).text("[+]");
     }
     else {
       $(panelId).slideUp('normal');
       $(buttonId).text("[-]");
     }
   }

Now pass the panel or block id which you want to hide/show and button id which will cause hide/show.

onclick="showHideBlock('#MyPanel', '#MyPanelExpandCollapseButton');"

Try this

Upvotes: 1

Faizan Ali
Faizan Ali

Reputation: 13

create a separate .js file and include it in whichever page you want. however remember to keep the id same :3

Upvotes: 0

Related Questions