Search code examples
javascriptonmouseoverboxdrop

Creating a simple dropdown with 'onmouseover'


Hi I just want a small box to drop down when I mouse over an element, and I want it go away when I mouse out. Where am I going wrong?

My HTML:

 <div onmouseover = 'mouseOverToggle()' onmouseout = '//function' id = 'new' class = 'child new'> New
     <div  id ='newDropDown' class="new dropdown"><a href=""></a></div> 
 </div>

Javascript:

var newDropdown = document.getElementById('new');
var dropDownContent = document.getElementById('newDropDown');

dropDownContent.style.display = 'none'

newDropdown.addEventListener('mouseover', mouseOverToggle);

function mouseOverToggle() {
   dropDownContent.style.display === 'none' ? 'show' : 'none' 
}

Solution

  • There were a couple of things in your code that I changed. This works, though:

    var dropDownContent = document.getElementById('newDropDown');
    dropDownContent.style.display = 'none';
    function mouseOverToggle() {
       dropDownContent.style.display = "";
    }
    function mouseOutToggle() {
       dropDownContent.style.display = "none";
    }
     <div onmouseover='mouseOverToggle()' onmouseout='mouseOutToggle()' id='new' class='child new'>Mouse over this!
       <div id='newDropDown' class="new dropdown">
         <a href="#">First option</a>
       </div>
     </div>

    You asked where you went wrong, though, so here's the stuff that was actually preventing it from working:

    • The <a> tag was empty, so you couldn't see it.
    • There were a couple of missing semicolons.
    • Instead of === (used when comparing exactly), use = to assign something to a property/variable.
    • The ternary wasn't working, because 'none' couldn't tell whether you moused over it; it's just the string none.

    (The rest of the stuff that wasn't needed I won't mention, however I did remove it.)