Created
January 10, 2019 09:32
-
-
Save shibbirweb/c75bdf50325f196b8145e3a6098dea5a to your computer and use it in GitHub Desktop.
jQuery Sidebar Toggle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Sidebar Show Hide</title> | |
<style type="text/css"> | |
.sidebar{ | |
position: fixed; | |
background-color: #dcdcdc; | |
height: 100%; | |
right: -300px; | |
width: 300px; | |
} | |
.active{ | |
right: 0px; | |
} | |
</style> | |
</head> | |
<body id="body"> | |
<button id="button">Right Sidebar</button> | |
<div class="sidebar"> | |
<ul> | |
<li><a href="#">First Element</a></li> | |
<li><a href="#">Second Element</a></li> | |
<li><a href="#">Third Element</a></li> | |
<li><a href="#">Fourth Element</a></li> | |
<li><a href="#">Fifth Element</a></li> | |
</ul> | |
</div> | |
<script | |
src="https://code.jquery.com/jquery-3.3.1.min.js" | |
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" | |
crossorigin="anonymous"></script> | |
<script type="text/javascript"> | |
$(document).ready(function(){ | |
//method calling | |
sidebarToggle('#button', '.sidebar', 'active'); | |
/** | |
* Sidebar Toggle Function | |
* @param {String} clickElement Where event call [Example: #button] | |
* @param {String} sidebarElement Sidebar id or class [Example: .sidebar] | |
* @param {String} sidebarClass Element class name without dot [Example: active] | |
* @param {String} eventName Optional event name. default is click. [Example: click] | |
* @return {void} | |
*/ | |
function sidebarToggle(clickElement, sidebarElement, sidebarClass, eventName='click') { | |
$(clickElement).on(eventName, function(){ | |
var sidebar = $(sidebarElement); | |
if (sidebar.hasClass(sidebarClass)) { | |
sidebar.removeClass(sidebarClass); | |
}else{ | |
sidebar.addClass(sidebarClass); | |
} | |
}); | |
$(document).on(eventName, function (event) { | |
var value = $(event.target).closest(clickElement + ',' + sidebarElement).length; | |
if (value == 0) { | |
if ($(sidebarElement).hasClass(sidebarClass)) { | |
$(sidebarElement).removeClass(sidebarClass); | |
} | |
} | |
}); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment