HOW TO CREATE A CLICKABLE DROPDOWN

z33

Tsaxmesa

New Member
Aug 26, 2018
19
66
21
Ibadan
Create a Clickable Dropdown
Create a dropdown menu that appears when the user clicks on a button.

Step 1) Add HTML:
Example
HTML:
<div class="dropdown">
<buttononclick="myFunction()"class="dropbtn">Dropdown</button>
<div id="myDropdown"class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
Example Explained
Use any element to open the dropdown menu, e.g. a <button>, <a> or <p> element.

Use a container element (like <div>) to create the dropdown menu and add the dropdown links inside it.

Wrap a <div> element around the button and the <div> to position the dropdown menu correctly with CSS.

Step 2) Add CSS:
Example
HTML:
 .dropbtn { background-color:#3498DB; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer;
}

.dropbtn:hover, .dropbtn:focus { background-color:#2980B9;
}

.dropdown { position: relative; display: inline-block;
}

.dropdown-content { display: none; position: absolute; background-color:#f1f1f1; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1;
}

.dropdown-content a { color: black; padding: 12px 16px; text-decoration:none; display: block;
}

.dropdown-content a:hover {background-color: #ddd}

.show {display:block;}
Step 3) Add JavaScript:
Example

function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}

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;
if(openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
 
Last edited by a moderator: