I have a slide toggle that slides from right to left. I have some div elements
and I want when clicking on them slideToggle
only show and doesn't close on click again that div element
. Only close when clicking to button in slideToggle
How can i do that? Here is my detailed code jsfiddle
CodePudding user response:
I've transferred your jsfiddle to the StackOverflow code snippet below.
I've added an additional function slideOpen()
to the code. The function checks to see if is_collapsed
is true
. If the condition is met, the function will open the slider.
The trick here is to set is_collapsed
to false
at the end of the function so it doesn't run the animation again and close the slider.
Now, the only way to close the slider is by clicking the open/close button that uses your slideToggle()
function.
Please, run the snippet below to see this code in action. I've also added some comments to the slideOpen()
function to explain what's happening.
var easing = 1;
var animation_speed = 200;
var slider_width;
var is_collapsed = true;
function slideToggle() {
is_collapsed = $('#btn').css("margin-right") == slider_width "px" && !$('#btn').is(':animated');
var sign = (is_collapsed) ? '-' : ' ';
if (!$('#btn').is(':animated')) {
if (easing) $('.willSlide').animate({
"margin-right": sign '=' slider_width
}, animation_speed);
else $('.willSlide').animate({
"margin-right": sign '=' slider_width
}, animation_speed);
}
(is_collapsed) ? $('.willSlide').removeClass('expanded'): $('.willSlide').addClass('expanded');
}
//function to open slide
function slideOpen() {
//if is_collapsed is true, animate div and open slider
if (is_collapsed) {
var sign = ' '
$('.willSlide').animate({
"margin-right": sign '=' slider_width
}, animation_speed);
//add expanded class to button when opened
$('.willSlide').addClass('expanded')
//set is_collapsed to false so it won't close slider on additional clicks
is_collapsed = false
}
}
$(document).ready(function() {
slider_width = $('#content').width(); //get width automaticly
$('#btn').click(slideToggle);
});
#content {
position: fixed;
height: 100%;
background: rgb(97, 97, 97);
width: 200px;
right: 0px;
margin-right: -200px;
}
#btn {
position: fixed;
width: 100px;
right: 0px;
background: rgb(117, 231, 117);
top: 100px;
border-radius: 5px 0px 0 5px;
color: #fff;
text-align: center;
padding: 40px 0;
cursor: pointer
}
.expandedTxt {
display: none
}
#btn.expanded .expandedTxt {
display: block
}
#btn.expanded .click {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div onclick="slideOpen()">button1</div>
<div onclick="slideOpen()">button2</div>
<div id='content'></div>
<div id='btn'>
<span >open</span>
<span >close</span>
</div>