danielstocks / jQuery-Collapse

A lightweight (~1kb) jQuery plugin that enables expanding and collapsing content
http://webcloud.se/jQuery-Collapse/
MIT License
679 stars 153 forks source link

using an arbitrary link #85

Closed steveops closed 9 years ago

steveops commented 9 years ago

hi, i cant seem to get some custom link on a page to toggle some custom div on the same page, here is my code, tell me if there is anything wrong. I have tested the script files to know they are correctly loaded:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="js/libs/jquery/jquery.js"></script>
        <script type="text/javascript" src="plugins/collapse-plugin/jquery.collapse.js"></script>
        <style type="text/css">
            .has_link{
                background-color: #c9c9c9;
            }
            .has_target{
                background-color: #c9c9c9;
            }
            #target{
                background-color: #a9a9a9;
            }
        </style>
    </head>
    <body>
        <div>
            <div class="has_link">
                This 
                <a href="#target" id="toggler">link</a> should work
            </div>
            <div class="has_target">
                This div will not get toggled when the link above above is clicked
                <div id="target" data-collapse>
                    This div is the target of a collapse operation.                
                </div>
                This is still part of the outer div that wont be affected by the link above
            </div>
        </div>
        <script type="text/javascript">
            $(document).ready(function() {
                $(".has_link #toggler").click(function() {
                    $(this.hash).trigger("toggle");
                });
            });
        </script>
    </body>
</html>
danielstocks commented 9 years ago

Your JavaScript code works but there are two problems.

  1. Script files has be loaded after closing body tag in order for the inline data-collapse attribute to work.
  2. The markup needs to look something like this:

http://jsfiddle.net/t8htg70r/1/

cheers

steveops commented 9 years ago

i didn't know i have to maintain that pair of elements even in this case, thanks for helping.