I have wrote two js scripts, both of them work but the problem is only the one placed second in the code will work

i am trying to develop an eCommerce website for the first time but in here i wrote two scripts

As you can see in the pictures, it works well but only the one placed second will work on the website,
first image the dropdown script works
second one the scroll finction works

//show dropdowns//

function myFunction(a) {
    a.parentNode.getElementsByClassName('dropdown-content')[0].classList.toggle("show");
}

//click anywhere to hide dropdown//
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');
            }
        }
    }
};



window.onscroll = function () {
    myFunction();
};

function myFunction() {
    if (document.documentElement.scrollTop > 50) {
        document.getElementById("tph").className = "scrolled";
    } else {
        document.getElementById("tph").className = "header_top";
    }
}

>Solution :

Try to change the name of one of your functions to prevent overwriting.

JavaScript supports overriding not overloading, meaning, that if you define two functions with the same name, the last one defined will override the previously defined version and every time a call will be made to the function, the last defined one will get executed.

function myFunction(a) {
    a.parentNode.getElementsByClassName('dropdown-content')[0].classList.toggle("show");
}

//click anywhere to hide dropdown//
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');
            }
        }
    }
};



window.onscroll = function() {
    myFunction2();
};

function myFunction2() {
    if (document.documentElement.scrollTop > 50) {
        document.getElementById("tph").className = "scrolled";
    } else {
        document.getElementById("tph").className = "header_top";
    }
}

Leave a Reply