0

I have the following JavaScript/JQuery code which should make the div SideBar appear on the screen and become 1/5th the size of the body. I'm getting no errors in Firefox/Chrome console, and havve no idea why it isn't working. If I move the body of my first toggle method into the method itself it works fine, so I'm assuming I'm using the toggle method wrong.

var bodyHeight = $(window).height();
var bodyWidth = $(window).width();
sideWidth = bodyWidth / 5;

function slideSideBar() {
    $('#SideBar').toggle(
        function() {
            $("#SideBar").animate({
                opacity: 0.6,
                width: sideWidth
            }, 600);
        }, 
        function() {
            $("#SideBar").animate({
                opacity: 0,
                width: 0
            }, 600);
        });
}

The CSS is:

#SideBar { 
    height: 100%;
    width: 0%;
    opacity: 0;
    font-family: Arial, Tahoma, Verdana;
    color: white; 
    background-color: black;
}
Connor Cartwright
  • 385
  • 2
  • 3
  • 14

1 Answers1

1

As of jQuery 1.8, the toggle event (the version of toggle that accepted two functions) was deprecated, and as of 1.9, it was removed. More in this question and its answers.

To get the old toggle behavior, maintain your own flag (or in your case, check the opacity) and call the toggle method (not event) yourself.

Here's the flag method, since it may be more appropriate to an animate situation (note the use of stop, which you probably wanted even in <=1.8):

var bodyHeight = $(window).height();
var bodyWidth = $(window).width();
sideWidth = bodyWidth / 5;

function slideSideBar() {
    var sidebar = $("#SideBar");
    var flag = sidebar.css("opacity") != 0;

    sidebar.click(function() {
        var options = flag ? {opacity: 0, width: 0} : {opacity: 0.6, width: sideWidth};
        flag = !flag;
        sidebar.stop(true, true).animate(options, 600);
    });
}

Or actually, checking opacity is fine after the stop:

var bodyHeight = $(window).height();
var bodyWidth = $(window).width();
sideWidth = bodyWidth / 5;

function slideSideBar() {
    $("#SideBar").click(function() {
        var sidebar = $(this);
        sidebar.stop(true, true);
        sidebar.animate(
            sidebar.css("opacity") != 0 ? {opacity: 0, width: 0} : {opacity: 0.6, width: sideWidth},
            600
        );
    });
}
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875