I have several links in the menu. Each link is making opacity from 0 to 1 for hidden div. I made dropdown menu this way because I use flex inside that div so I toggle the opacity.
I am using document.getElementsByClassName for selecting an elements. When someone is making a variable with this selector basically he or she has an array with all of the elements with this class.
My code is working, because when I envoke the function from HTML, I'm doing it using parameters. What I would like to do is to connect the link I'm clicking and the div that it shows by index. For example, all links with class A are opening divs with class B. I want to be sure that the first link with class A always opens the first link with class B. I don't want to rely on the parameters in HTML.
How can I do it more efficiently?
function showDropDown(n) {
let hiddenDiv = document.getElementsByClassName("hidden_dropdown_div");
hiddenDiv[n].classList.toggle("active");
for (let i = 0; i < hiddenDiv.length; i++) {
if (i != n) {
hiddenDiv[i].classList.remove("active")
};
}
};
$(".maindrop_link").click(function(e) {
e.stopPropagation(); // This is the preferred method.
return false; // This should not be used unless you do not want
// any click events registering inside the div
});
$(document).click(function() {
let hiddenDiv = document.getElementsByClassName("hidden_dropdown_div");
for (let i = 0; i < hiddenDiv.length; i++) {
hiddenDiv[i].classList.remove("active");
}
});
.hidden {
opacity: 0;
}
.active {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- See the link above the hidden block -->
<li class="dropmenu inlineblock">
<a class="maindrop_link" href="#" onclick="showDropDown(0)">Makeup</a>
</li>
<div class="hidden_dropdown_div hidden" id="hidden_dropdown_div">
<div class="hidden_dropdown_link_wrapper">
<ul class="hidden_dropdown_ul">
<li><a class="hiddendrop_link" href="#">Wedding Makeup</a></li>
<li><a class="hiddendrop_link" href="#">Event Makeup</a></li>
<li><a class="hiddendrop_link" href="#">Creative Makeup</a></li>
</ul>
</div>
<div class="hidden_dropdown_pic_wrapper">
<div class="item_for_hidden_div">
<div class="picholder_for_hidden_div"></div>
<div class="textholder_for_hidden_div"></div>
</div>
<div class="item_for_hidden_div">
<div class="picholder_for_hidden_div"></div>
<div class="textholder_for_hidden_div"></div>
</div>
<div class="item_for_hidden_div">
<div class="picholder_for_hidden_div"></div>
<div class="textholder_for_hidden_div"></div>
</div>
</div>
</div>