0

I have a div that slides in using a toggle. I would like the user to be able to click the toggle which slides in the div and then if they click outside of #hiddenpanel the #hiddenpanel slides out of screen.

I currently have the div sliding in and out using the toggle, i just need to make it so when the user clicks outside of the div (once it has slid in) the div slides back out...

Hope this makes any sense!

Here is my JQuery code so far:

var speed = 800;
    $('#close-bar').on('click', function(){

        var $$ = $(this),
            panelWidth = $('#hiddenPanel').outerWidth();

        if( $$.is('.myButton') ){
            $('#hiddenPanel').animate({right:0}, speed);
            $$.removeClass('myButton')
        } else {
            $('#hiddenPanel').animate({right:-panelWidth}, speed);
            $$.addClass('myButton')
        }

    });

Here is the mark up :

<div id="hiddenPanel" class="txt-highlight-color bg-color bg-pattern">
</div>

Here is the URL : http://www.bboyrival.com/

The toggle is the 'Profile Info' text at the bottom right.

Thanks for your time.

DannyBoy
  • 1,604
  • 2
  • 13
  • 12
  • Have a look at the accepted answer in this post: http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element – ThomasK Feb 18 '14 at 13:34
  • @ThomasK How do i incorporate that into my code? I'm new to JQuery and have tried everything i can think of. I was looking at that other post for hours last night trying to figure it out but no luck! – DannyBoy Feb 18 '14 at 14:03
  • How'bout `$('html').click(function(){ $$.addClass('myButton'); }); });` - outside the function you have right there? (if `myButton` removes the panel, otherwise remove the class instead) – ThomasK Feb 18 '14 at 14:24

1 Answers1

0

Try the following changes in your code:

$("body").click(function(){
    $('#close-bar').removeClass('myButton');
    $('#hiddenPanel').animate({right:0}, speed);
})

var speed = 800;
$('#close-bar').on('click', function(event){

    event.stopPropagation();

    var $$ = $(this),
        panelWidth = $('#hiddenPanel').outerWidth();

    if( $$.is('.myButton') ){
        $('#hiddenPanel').animate({right:0}, speed);
        $$.removeClass('myButton')
    } else {
        $('#hiddenPanel').animate({right:-panelWidth}, speed);
        $$.addClass('myButton')
    }

});

What these changes do is:

  • add a click event to body to close #hiddenPanel and remove the class 'myButton' from #close-bar
  • and prevent the click on #close-bar to bubble up to body.

you could add to the body click event a check to see if the panel is open, and if not to do nothing Hope this helps

R. Schifini
  • 9,085
  • 2
  • 26
  • 32
  • Unfortunately neither is working! Not sure why! Really wanna get this working though as it will make the site alot more user friendly. I have tried changing the "body" with other options such as "html" but still no luck. not sure what i'm doing wrong! – DannyBoy Feb 19 '14 at 18:01