Antti
Antti

Reputation: 313

If not hovering over element A or element B

I have dynamically constructed menu that I want to hide and show on hovering over the menu title. When the user is not hovering over the title OR the menu itself, the menu should close (animate height to 0).

I'm uncertain how to check if the user is hovering over either A or B.

This code worked when I was able to use .hover() but that one doesn't work on dynamically created elements, so now I'm attempting to use .on().

Here is my attempt:

var mychapterMenuTimer = false;

        $(document).on("mouseenter", "#chapterName, .chapterMenuContainer", (function() {
            //mouse enter
            clearTimeout(mychapterMenuTimer);
        }), function() {
            //mouse leav
            mychapterMenuTimer = setTimeout(function() {
                $('#chapterMenu').animate({
                    height: '0'
                }, 444);
            }, 100)
        });
#chapterMenu {  
    width: 70%;
    position: absolute;
    top: 40px;
    
    height: 0px;
    overflow: hidden;
 
    
}
<-- dynamically created earlier -->

<p class="chapterName">

<div id="chapterMenu" class="menuHover">
  <div class="row chapterMenuContainer">
    <div class="col-6 chapterList1"></div>
    <div class="col-6 chapterList2"></div>
  </div>
</div>

Upvotes: 1

Views: 103

Answers (1)

Jasmine
Jasmine

Reputation: 473

Assuming your classes and ID's don't also dynamically change, you can achieve all of this in your CSS file using the :hover selector and CSS transitions for animation effects, without twisting your brain around javascript logic.

See below example;

#chapterMenu {  
        width: 200px;
        position: absolute;
        top: 80px;
        height: 0px;
        background-color:#ddd;
        overflow: hidden;
            
        /*animate height*/

        transition: height 0.25s;
        -webkit-transition: height 0.25s;
    }
        
    .chapter { 
        display: inline-block;
        padding:10px 20px;
    }
    .chapter:hover #chapterMenu {
        /*on chapter name hover set chapterMenu height */
        height:100px;

    }
  <div class="chapter">
            <p>Chapter 1</p>

    <div id="chapterMenu" class="menuHover">
      <div class="row chapterMenuContainer">
        <div class="col-6 chapterList1"><a href="#">chapter1 list item 1</a></div>
        <div class="col-6 chapterList2"><a href="#">chapter1 list item 2</a></div>
      </div>
    </div>
            </div>
        <div class="chapter">
            <p>Chapter 2</p>

    <div id="chapterMenu" class="menuHover">
      <div class="row chapterMenuContainer">
        <div class="col-6 chapterList1"><a href="#">chapter2 list item 1</a></div>
          <div class="col-6 chapterList2"><a href="#">chapter2 list item 2</a></div>
      </div>
    </div>
            </div>

The only downside with CSS animations is limited support from older browsers.

Upvotes: 1

Related Questions