Home » Jquery » javascript – Jquery toggle sidebar with 2 buttons

javascript – Jquery toggle sidebar with 2 buttons

Posted by: admin February 22, 2020 Leave a comment

Questions:

I am trying to create a toggle on a sidebar so that the toggle button opens the sidebar. This works great on desktop, however, if I am using mobile, the toggle button gets hidden. Is it possible to add a close button in the sidebar which can close the sidebar without breaking the script? The script I have is:

<div id="sidebar">content</div>
<div id="filter-icon">Refine Selection <div id="filterswitch"></div></div>
<script>
jQuery(document).ready(function() {
    jQuery("#filter-icon").click(function() {
        jQuery("#filterswitch").toggleClass('active');
        jQuery("#sidebar").toggleClass('show-sidebar');
    });
});
</script>
How to&Answer:

Shouldn’t be a problem, have you tried something like this?

<div id="sidebar"><button id="closeSidebar">Close</button></div>
<div id="filter-icon">Refine Selection <div id="filterswitch"></div></div>

<script>
    const toggleSidebarAndSwitch = () => {
      jQuery("#filterswitch").toggleClass('active');
      jQuery("#sidebar").toggleClass('show-sidebar');
    }

    jQuery(document).ready(() => {
        jQuery("#filter-icon").click(() => {
          toggleSidebarAndSwitch()
        });
        jQuery("#closeSidebar").click(()=>{
          toggleSidebarAndSwitch()  
        })
    });
    </script>

Answer:

Yes it’s possible just add another div in your sidebar like this:

<div id="sidebar">
  content
  <div class="filterswitch"></div>
</div>
<div id="filter-icon">
  Refine Selection
  <div class="filterswitch"></div>
</div>

If you ad the class filterswitch to both div’s jQuery will automatically listen for clicks on both elements.