So I have got this code for my website, which I built myself and works fine. The thing is, that I want the JavaScript code 'cleaner'. I read that JavaScript was all about not-rewriting code. The problem is that I don't really know how to restructure the dropDownOne through dropDownSeven functions. Each of the functions corresponds to a particular button, which on click then shows the corresponding information block by applying the class 'show' on it, which only got one property: Display: block;
So to wrap it up: how do I get to rework the code, so that I only need say, one function for all the buttons to click on. If a particular button is clicked, that buttons content should show, and not that from the others.
-No jQuery-
HTML:
<div class="dropdown">
<button onclick="dropDownFour()" class="projectbuttons">
PSD to Bussiness Site (01-2017)
</button>
<div id="dropdownfour" class="dropdown-content">
<!--Content-->
</div>
</div>
JavaScript:
function dropDownOne() {
document.getElementById("dropdownone").classList.toggle("show");
}
function dropDownTwo() {
document.getElementById("dropdowntwo").classList.toggle("show");
}
function dropDownThree() {
document.getElementById("dropdownthree").classList.toggle("show");
}
function dropDownFour() {
document.getElementById("dropdownfour").classList.toggle("show");
}
function dropDownFive() {
document.getElementById("dropdownfive").classList.toggle("show");
}
function dropDownSix() {
document.getElementById("dropdownsix").classList.toggle("show");
}
function dropDownSeven() {
document.getElementById("dropdownseven").classList.toggle("show");
}
window.onclick = function (event) {
if (!event.target.matches('.aboutmebuttons, .projectbuttons,
#mailopenbutton, [name="name"],
[name="message"], ' + '[name="email"],
[name="submitmail"], [name="reset"],
#dropdownseven, #mailform')
) {
var dropDowns = document.getElementsByClassName("dropdown-content");
for (var i = 0; i < dropDowns.length; i++) {
var openDropDown = dropDowns[i];
if (openDropDown.classList.contains('show')) {
openDropDown.classList.remove('show');
}
}
}
}
Thanks!
function dropDown(id){
document.getElementById(id).classList.toggle("show");
}
And then you could use it like that
<div class="dropdown">
<button onclick="dropDown('dropdownfour')" class="projectbuttons">PSD to Bussiness Site (01-2017)</button>
<div id="dropdownfour" class="dropdown-content">
<!--Content-->
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With