-1

I have the following Jquery to show and hide divs with a button click. It works fine only on the first two clicks. After the second click a hashtag appears in the URL and the script doesn't work. I tried putting e.preventDefault() at the top of the method, but that prevents the click event from even working. What could possibly be wrong here?

<script>
$(document).ready(function () {
    $('.container').hide();
    $('.status-icon').text("+");

    $('#expandsections').click(function (e) {

        var allContentToggleContainers = $('.content-toggle .container');

        var allVisibleContentToggleContainers = allContentToggleContainers.filter(function () {
            return $(this).css("display") == "block";
        });

        if (allContentToggleContainers.length && allContentToggleContainers.length === allVisibleContentToggleContainers.length) {
            allContentToggleContainers.hide().next().slideUp();
            $('.status-icon').text("+");
        }
        else {
            allContentToggles.not('selector:visible').show().next().slideDown();
            $('.status-icon').text("+");
        }

        return false;
    });
});
</script>
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
Robert
  • 1,638
  • 7
  • 34
  • 45

2 Answers2

1

Here is a jsfiddle: http://jsfiddle.net/Grimbode/VTh5C/

It seems that "allContentToggles" should have been "allContentToggleContainers" instead.

The moment I switched them, the code started working as intended. Let me know if this is what you wanted.

$('.container').hide();
$('.status-icon').text("+");

$('#expandsections').click(function (e) {

    var allContentToggleContainers = $('.content-toggle .container');

    var allVisibleContentToggleContainers = allContentToggleContainers.filter(function () {
        return $(this).css("display") == "block";
    });

    if (allContentToggleContainers.length && allContentToggleContainers.length === allVisibleContentToggleContainers.length) {
        allContentToggleContainers.hide().next().slideUp();
        $('.status-icon').text("+");
    } else {
        allContentToggleContainers.not('selector:visible').show().next().slideDown();
        $('.status-icon').text("+");
    }

    return false;
});
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
0

This explanation might help you out:

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

What is your html in this scenario? (Mainly the expandsections - is it a div or an a tag?)

Community
  • 1
  • 1
PM1
  • 151
  • 5