简体   繁体   中英

JavaScript function does not fire

I am working on building a mobile page that uses JavaScript to make the top menu drop down and close as well, but it is not working. Here's the JS

<script>
window.onload = function () { 
var elem = document.getElementById('navBarMobile');
var burger = document.getElementById('hamburgerMobile');
var cross = document.getElementById('crossMobile');
}

function menuExpand() {

    elem.style.transition = "height 1s linear 0s";
    elem.style.height = "292px";

    burger.style.transition = "opacity 0.5s linear 0s";
    burger.style.opacity = "0";
    burger.style.zIndex = "0";

    cross.style.transition = "opacity 0.5s linear 0.5s"
    cross.style.opacity = "1";
    cross.style.zIndex = "1";
}

function menuClose() {

    elem.style.transition = "height 1s linear 0s";
    elem.style.height = "87px";

    burger.style.transition = "opacity 0.5s linear 0.5s";
    burger.style.opacity = "1";
    burger.style.zIndex = "1";

    cross.style.transition = "opacity 0.5s linear 0s";
    cross.style.opacity = "0";
    burger.style.zIndex = "0";
}
</script>

And the html

<div id="hamburgerMobile" onclick="menuExpand();"></div>
<div id="crossMobile" onclick="menuClose();"></div>

Before, I had the declaration statements seen at the top in their designated spots inside of the function, but each function was firing only once.

Variables elem , burger and cross are defined in different scope and it is not visible form your functions.

You should try to declare it earlier:

var elem;
var burger;
var cross;

window.onload = function () { 
  elem = document.getElementById('navBarMobile');
  burger = document.getElementById('hamburgerMobile');
  cross = document.getElementById('crossMobile');
}

Read about function scopes: http://www.w3schools.com/js/js_scope.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM