With jQuery You Can...
Explination
If you have multiple tags that need to be registered/delegated to an event, use .class
or <tagName>
-- using #id
is arduous and unnecessary.
$('.more-options').on('click', function() {...
Use $(this)
to reference the clicked tag and chain .find()
to reference it's descendants if needed. If a line gets too unwieldy, store it in a variable.
var clicked = $(this).find('.user-setting-drop');
When you want "accordion behavior", close/deactivate/collapse all tags (excluding the clicked tag by using .not()
), then open/activate/expand the clicked tag.
$('.user-setting-drop').not(clicked).removeClass('active');
clicked.toggleClass('active');
Demo 1
Uses .remove
/toggleClass()
methods. It involves more work with CSS if you want some animation.
$('.more-options').on('click', function() {
var clicked = $(this).find('.user-setting-drop');
$('.user-setting-drop').not(clicked).removeClass('active');
clicked.toggleClass('active');
});
.more-options {
cursor: pointer
}
.user-setting-drop {
max-height: 0;
color: transparent;
opacity: 0;
transition: all 0.5s;
}
.active {
height: auto;
max-height: 5000px;
color: #000;
opacity: 1;
transition: all 0.5s, max-height: 0.7s;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css">
<div class="more-options" id="PostMenu0">
<i class="fas fa-ellipsis-h"></i>
<div class="user-setting-drop" id="openDropMenu0">
<a href="#/" title="">Report</a>
</div>
</div>
<hr>
<div class="more-options" id="PostMenu1">
<i class="fas fa-ellipsis-h"></i>
<div class="user-setting-drop" id="openDropMenu1">
<a href="#/" title="">Report</a>
</div>
</div>
<hr>
<div class="more-options" id="PostMenu2">
<i class="fas fa-ellipsis-h"></i>
<div class="user-setting-drop" id="openDropMenu2">
<a href="#/" title="">Report</a>
</div>
</div>
<hr>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Demo 2
Uses .slideToggle
/Up()
methods. It involves less work with animation already built in.
$('.more-options').on('click', function() {
var clicked = $(this).find('.user-setting-drop');
$('.user-setting-drop').not(clicked).slideUp(300);
clicked.slideToggle(500);
});
.more-options {
cursor: pointer;
}
.user-setting-drop {
display: none
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css">
<div class="more-options" id="PostMenu0">
<i class="fas fa-ellipsis-h"></i>
<div class="user-setting-drop" id="openDropMenu0">
<a href="#/" title="">Report</a>
</div>
</div>
<hr>
<div class="more-options" id="PostMenu1">
<i class="fas fa-ellipsis-h"></i>
<div class="user-setting-drop" id="openDropMenu1">
<a href="#/" title="">Report</a>
</div>
</div>
<hr>
<div class="more-options" id="PostMenu2">
<i class="fas fa-ellipsis-h"></i>
<div class="user-setting-drop" id="openDropMenu2">
<a href="#/" title="">Report</a>
</div>
</div>
<hr>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>