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;
}
2
  • How is slideSideBar called? and do you have the code in a dom ready handler ? Commented Jun 29, 2014 at 22:36
  • @karthikr I have a menu icon in my HTML code, which has the onclick event to call the function slideSideBar() Commented Jun 29, 2014 at 23:11

1 Answer 1

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
        );
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.