Nik Hendricks
Nik Hendricks

Reputation: 31

Hiding and showing sidebar div

I have a site here and I want to hide and show the sidebar with a button in the header but it is not working. Here is what I have tried:

<div id="B">
    <button>toggle</button>
</div>
$('button').toggle(function() {
    $('#sidebarright').animate({ left: 0 })
}, function() {
    $('#sidebarright').animate({ left: 200 })
})

Nothing happens. Could you help me find out the problem?

Upvotes: 1

Views: 807

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The toggle() functionality you're trying to use has now been deprecated and removed from the latest versions of jQuery. To replicate it you can use the click() event with a simple ternary expression. Try this:

$('button').click(function() {
    var $el = $('#sidebarright');
    $el.animate({
        left: parseInt($el.css('left'), 0) == 0 ? 200 : 0
    });
});

Also note that the page you link to on your website does not contain a reference to jQuery. Here's how you should do that, along with a full implementation of the above code:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script>
        $(function() {
            $('button').toggle(function() {
                var $el = $('#sidebarright');
                $el.animate({
                    left: parseInt($el.css('left'), 0) == 0 ? 200 : 0
                });
            });
        });
    </script>
</head>

Also note that you can simplify this by using CSS transitions only and toggling a class:

#sidebarright {
    /* UI styling rules here */
    left: 0;
    transition: left 0.5s
}
#sidebarright.open {
    left: 200;
}
$('button').click(function() {
    $('#sidebarright').toggleClass('open');
});

Upvotes: 1

elementsCSS
elementsCSS

Reputation: 1

You are using jQuery Script but you have not attached jQuery file in header. Please add jQuery File in header.

Download it from http://www.jquery.com

Upvotes: 0

Related Questions