Ad

Loop Through Nav Menu When Li Menu's Hovered

- 1 answer

I am not familar with JavaScript DOM , mostly i use jQuery for script.. I am trying on JavaScript and in trouble with the below code. Does anyone know what could be the problem?

What i would like to do is when LI is hovered, the nested OL is displayed..somehow, the below code doesn't work, even it doesn't show any error in console.

Please help me...

var ul = document.querySelector('.gnb');
var li = ul.children;
var ol = document.getElementsByTagName('ol');
var i;

for (i = 0; i < li.length; i++) {
  li[i].addEventListener('mouseenter', myFunction(myshow));
  li[i].addEventListener('mouseleave', myFunction(myhide));
}

function myshow() {
  ol.style.display = 'block'
}

function myhide() {
  ol.style.display = 'none'
}

function myFunction(fn) {
  return function(e) {
    if (e.target.type !== "mouseenter") return;
    fn.call(e.target)
  };
}
.gnb {
  float: left;
  margin-left: 30px;
  width: auto;
  height: 100%;
}

.gnb>li {
  float: left;
  width: 150px;
  height: 100%;
  list-style: none;
}

.sub {
  display: none;
}

.sub.show {
  display: block;
}
<ul class="gnb">
  <li class="gnbLi">
    <a target="_blank" rel="nofollow noreferrer" href="#">Why Mailchimp?</a>
  </li>
  <li class="gnbLi" onmouseenter="myFunction()">
    <a target="_blank" rel="nofollow noreferrer" href="#">What You Can Do</a>
    <ol class="sub">
      <li><a target="_blank" rel="nofollow noreferrer" href="#">Overview</a></li>
      <li><a target="_blank" rel="nofollow noreferrer" href="#">Create</a></li>
    </ol>
  </li>
</ul>

Ad

Answer

Problem: Basically what you have done is dealing with an array as a single element because of getElementsByTagName returns an array of ol in the whole page.


Solve: 1. you need to get the nested ol inside the li that's being hovered using -event.target to get the clicked li. - querySelector to get the ol under that li. 2. you need the ol to be displayed/removed depending on the event.


so only change the Javascript to be as the following and it will work

var ul = document.querySelector('.gnb');
var li = ul.children;

for (i = 0; i < li.length; i++) {
  li[i].addEventListener('mouseenter', mouseenter);
  li[i].addEventListener('mouseleave',mouseleave );
}

function mouseenter(event) {
	var ol = event.target.querySelector('ol');
  if(ol){
    ol.style.display = 'block';
  }
}

function mouseleave(event) {
	var ol = event.target.querySelector('ol');
  if(ol){
    ol.style.display = 'none';
  }
}

Ad
source: stackoverflow.com
Ad