Add a click functionality to sidebar without affecting its toggle feature

574 views Asked by At

I have a sidebar and I have a button which toggles the sidebar on click. I have a jQuery function which does that. I have a new functionality now, where, if the sidebar is open and the user clicks any of the list items in the sidebar, it toggles back and some function will be excecuted.

The Problem:

When I click the li inside the sidebar, the toggle button is waiting for it's second click (my guess). So if I add toggle on clicking sidebar li, the main toggle button functionality breaks. How do I keep both without affecting each other. I hope I have made myself clear. Here is the code.

JS

// code for sidebar toggle in jQuery
$.fn.toggleClick = function () {
    var methods = arguments,
        count = methods.length;
    return this.each(function (i, item) {
        var index = 0;
        $(item).on('click', function () {
            return methods[index++ % count].apply(this, arguments);
        });
    });
};

//for opening sidebar
function openSidebar() {
    $('#sg-evm-sidebar').animate({
        left: 0
    }, 300)
    $('.container').css({
        position: "fixed"
    }).animate({
        left: 300
    }, 300)
    $('.content-overlay').delay(300).show();
}
//closing sidebar
function closeSidebar() {
    $('#sg-evm-sidebar').animate({
        left: -300
    }, 300)
    $('.container').css({
        position: "fixed"
    }).animate({
        left: 0
    }, 300)
    $('.content-overlay').delay(300).hide();
}

//$(".empName").on("click", function () {
//   closeSidebar();
//});

// calling toggleclick here
$('.toggle-box').toggleClick(openSidebar, closeSidebar);  

Here is a JS FIDDLE. I created it from my huge website. So please ignore broken images.

2

There are 2 answers

3
jcuenod On BEST ANSWER

I've updated your fiddle: http://jsfiddle.net/qvksx30g/4/

I've added some basic logic

var sidebarOpen = false;

function toggleSidebar()
{
    if (sidebarOpen)
        closeSidebar();
    else
        openSidebar();
}

And then inside openSidebar and closeSidebar I set sidebarOpen.

I also no longer use toggleClick. Instead I'm using:

$(document).on('click', '.toggle-box', toggleSidebar)
  .on('click', '.list li', closeSidebar);
1
Florian Motteau On

You could keep track of the sidebar state (open or close) using a class on the sidebar wrapper ("close" or "open"), and then use this class to determine in your click listener if you have to call closeSidebar or openSidebar.