jqueryaccordionjquery-hoverjquery-on

.hover Works, On Click doesn't


So this has caused me a lot of headace. I am making a "pulldown accordion submenu" (for the lack of a better name). My script works, but only on HOVER. If I try to use .click, .on("click"), .on("click", "li") etc. nothing works. The script only works when using .hover.

NOTE! It's only the "#TopMenu" that is supposed to have the on click event. The sub-menu ("#accordion") is going to be hover.

Any ideas ?

Working:

$(document).ready(function () {

    $('#accordion li').hover(function () {
        $(this).find('ul').stop(true, true).slideDown()
    }, function () {
        $(this).find('ul').stop(true, true).slideUp()
    }).find('ul').hide()

$('#TopMenu li').hover(function() {

        $(this).find('li').stop(true, true).slideDown()
    }, function () {
        $(this).find('li').stop(true, true).slideUp()
    }).find('li').hide()

});

Changing "#TopMenu" to CLICK is NOT WORKING:

$(document).ready(function () {

    $('#accordion li').hover(function () {
        $(this).find('ul').stop(true, true).slideDown()
    }, function () {
        $(this).find('ul').stop(true, true).slideUp()
    }).find('ul').hide()

$('#TopMenu li').on('click', function() {

        $(this).find('li').stop(true, true).slideDown()
    }, function () {
        $(this).find('li').stop(true, true).slideUp()
    }).find('li').hide()

});

I have a working test here: http://jsbin.com/nidazuq/3/embed?html,js,output

I'm going nuts over this, I've searched high and low for a solution. please help.


Solution

  • ID should be unique and single for a page. You used twice in the page. Added fiddle with some changes.

    $('#TopMenu li').on('click', function() {
      $(this).children('ul').slideToggle();
    });
    $("#TopMenu li ul li > a").hover(function(){
      $(this).next('ul').slideToggle();
    })
    #TopMenu li ul, .firstStep ul ul, .firstStep ul{display:none}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul id="TopMenu">
      <li><a href="#" class="menu_heading" rel="menu_heading">CLICK ME</a>
        <ul id="accordion">
          <li> <a href="#" class="history_heading" rel="history_heading">HISTORY</a>
            <ul>
              <li><a href="#">Link One</a></li>
              <li><a href="#">Link Two</a></li>
              <li><a href="#">Link Three</a></li>
              <li><a href="#">Link Four</a></li>
              <li><a href="#">Link Five</a></li>
            </ul>
          </li>
          <li> <a href="#" class="geography_heading" rel="geography_heading">GEOGRAPHY</a>
            <ul>
              <li><a href="#">Link One</a></li>
              <li><a href="#">Link Two</a></li>
              <li><a href="#">Link Three</a></li>
              <li><a href="#">Link Four</a></li>
              <li><a href="#">Link Five</a></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>