Stack Overflow Asked by carrey on December 3, 2021
I’ve found a simple javascript onclick function below.
function dropdownFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
<div class="dropdown">
<button onclick="dropdownFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>
When I try the below html code, dropdown content doesn’t pop up.
<div class="dropdown">
<div class="dropbtn" onclick="dropdownFunction()">
<%= image_tag "global-icon.png", alt: 'Language' %>
<i class="icon-down-dir"></i>
</div>
</div>
Please advise what I’m missing or wrong.
Updates
I changed to jquery instead and it’s working flawlessly.
$(document).ready(function(){
$('#droptoggle').click(function(event){
event.stopPropagation();
$("#myDropdown").slideToggle("1000");
});
$("#myDropdown").on("click", function (event) {
event.stopPropagation();
});
});
//close when click out of window
$(document).on("click", function () {
$("#myDropdown").hide();
});
function dropdownFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
#myDropdown {
display: none;
}
#myDropdown.show
{
display: block;
}
<div class="dropdown">
<button onclick="dropdownFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>
added CSS part here,
Answered by CodeBug on December 3, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP