Rief
Rief

Reputation: 451

convert hover to click toggle

i want to convert from hover to mouse click, here's some of the code

HTML

<li class="has-dropdown">
    <a href="#">Click Me</a>
        <ul class="dropdown">
            <li><a href="#">Web Design</a></li>
            <li><a href="#">eCommerce</a></li>
            <li><a href="#">Linux</a></li>
            <li><a href="#">API</a></li>
        </ul>
</li>

and here's the script but still in mouseover/mouseleave

var dropdown = function() {

    $('.has-dropdown').mouseenter(function(){

        var $this = $(this);
        $this
            .find('.dropdown')
            .css('display', 'block')
            .addClass('animated-fast fadeInUpMenu');

    }).mouseleave(function(){
        var $this = $(this);

        $this
            .find('.dropdown')
            .css('display', 'none')
            .removeClass('animated-fast fadeInUpMenu');
    });

};

dropdown()

How can I change this from hover to click?

Upvotes: 0

Views: 366

Answers (2)

hgb123
hgb123

Reputation: 14891

You could use .click with .toggleClass

$('#toggle').click(function() {
  $('.has-dropdown')
    .find('.dropdown')
    .css({
      display: function(_, value) {
        return value === 'none' ? 'block' : 'none'
      }
    })
    .toggleClass('animated-fast fadeInUpMenu')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="has-dropdown">
  <a id="toggle" href="#">Click Me</a>
  <ul class="dropdown">
    <li><a href="#">Web Design</a></li>
    <li><a href="#">eCommerce</a></li>
    <li><a href="#">Linux</a></li>
    <li><a href="#">API</a></li>
  </ul>
</li>

Upvotes: 1

Silvia
Silvia

Reputation: 56

You can use the onclick="YourFunction()" and it will execute the function only when you click it.

Not sure if this is what you want, but see this example

HTML

<input type="button"  value="Click me" onclick="showlist()" />

    <div id="list"  style="display:none;" > 
    
              <ul class="dropdown" type="hidden">
                <li><a href="#">Web Design</a></li>
                <li><a href="#">eCommerce</a></li>
                <li><a href="#">Linux</a></li>
                <li><a href="#">API</a></li>
            </ul>
    </div>

JS

function showlist() {
  var x = document.getElementById("list");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

http://jsfiddle.net/5an2mo0g/4/

Upvotes: 1

Related Questions