0

This my code but not work if i put slide way inside variable.

just fade in and out working

$('.sidebar-toggle').on('click', function(){

    if( $('.sidebar-left').length > 0 ) {
        var SideWay = 'left';
        var Sidebar = $('.sidebar-left');
    } else {
        var SideWay = 'right';
        var Sidebar = $('.sidebar-right');
    }

    var SidebarWidth = Sidebar.css('width');

    if( Sidebar.css('display') == 'none' )
    {
        Sidebar.fadeIn('fast').animate({ SideWay : '0'}, 400);
    } else {
        Sidebar.stop().animate({ SideWay : '-' + SidebarWidth}, 500).fadeOut();
    }

});
Mahmoud.ryan
  • 32
  • 1
  • 6
  • I guess this is because, `SlideWay` is defined inside `if`, so it looses its scope – Rajesh Nov 11 '15 at 05:08
  • `var val={}; val[SideWay]='-' + SidebarWidth; Sidebar.stop().animate(val, 500).fadeOut();` – Pranav C Balan Nov 11 '15 at 05:10
  • @Rajesh I don't think so. JS don't have block scope. And `SideWay` is defined in both `if` and `else`, so in any condition it'll always be defined. – Tushar Nov 11 '15 at 05:10
  • Setting CSS property `right=0` only has the expected effect in a limited set of scenarios. 1. I'm prerty sure you havent coded your CSS properly for this to work the way you want. 2. I think you should actually not rely on setting the css `right` property at all. You should delete the `SideWay` variable then force yourself to write this assuming you can only change the css `left` property. – Femi Nov 11 '15 at 05:17
  • Can you create live demo – Tushar Nov 11 '15 at 05:23

1 Answers1

0

try this

$('.sidebar-toggle').on('click', function(){

    if( $('.sidebar-left').length > 0 ) {
        var SideWay = 'left';
        var Sidebar = $('.sidebar-left');
    } else {
        var SideWay = 'right';
        var Sidebar = $('.sidebar-right');
    }
    var animateIt = {};
    var SidebarWidth = Sidebar.css('width');

    if( Sidebar.css('display') == 'none' )
    {
        animateIt[SideWay] = '0';
        Sidebar.fadeIn('fast').animate( animateIt , 400);
    } else {
        animateIt[SideWay] = '-' + SidebarWidth;
        Sidebar.stop().animate( animateIt , 500).fadeOut();
    }

});

you can take a look at this Using a variable for a key in a JavaScript object literal

while I don't know your full code this is just an Example of how it works

Community
  • 1
  • 1
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28