[javascript] JQuery show and hide div on mouse click (animate)

This is my HTML code:

<div id="showmenu">Click Here</div>
<div class="menu" style="display: none;">
    <ul>
        <li>Button1</li>
        <li>Button2</li>
        <li>Button3</li>
    </ul>
</div>

And I want to show .menu on click on #showmenu sliding from left to right (with animate). On click again on #showmenu or anywhere in site page, .menu will hide (slide back to left).

I use JQuery 2.0.3

I've tried this, but it doesn't do what I want.

$(document).ready(function() {
    $('#showmenu').toggle(
        function() {
            $('.menu').slideDown("fast");
        },
        function() {
            $('.menu').slideUp("fast");
        }
    );
});

This question is related to javascript jquery jquery-ui jquery-effects

The answer is


Of course slideDown and slideUp don't do what you want, you said you want it to be left/right, not top/down.

If your edit to your question adding the jquery-ui tag means you're using jQuery UI, I'd go with nnnnnn's solution, using jQuery UI's slide effect.

If not:

Assuming the menu starts out visible (edit: oops, I see that isn't a valid assumption; see note below), if you want it to slide out to the left and then later slide back in from the left, you could do this: Live Example | Live Source

$(document).ready(function() {
    // Hide menu once we know its width
    $('#showmenu').click(function() {
        var $menu = $('.menu');
        if ($menu.is(':visible')) {
            // Slide away
            $menu.animate({left: -($menu.outerWidth() + 10)}, function() {
                $menu.hide();
            });
        }
        else {
            // Slide in
            $menu.show().animate({left: 0});
        }
    });
});

You'll need to put position: relative on the menu element.

Note that I replaced your toggle with click, because that form of toggle was removed from jQuery.


If you want the menu to start out hidden, you can adjust the above. You want to know the element's width, basically, when putting it off-page.

This version doesn't care whether the menu is initially-visible or not: Live Copy | Live Source

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="showmenu">Click Here</div>
<div class="menu" style="display: none; position: relative;"><ul><li>Button1</li><li>Button2</li><li>Button3</li></ul></div>
  <script>
    $(document).ready(function() {
        var first = true;

        // Hide menu once we know its width
        $('#showmenu').click(function() {
            var $menu = $('.menu');
            if ($menu.is(':visible')) {
                // Slide away
                $menu.animate({left: -($menu.outerWidth() + 10)}, function() {
                    $menu.hide();
                });
            }
            else {
                // Slide in
                $menu.show().css("left", -($menu.outerWidth() + 10)).animate({left: 0});
            }
        });
    });
  </script>
</body>
</html>

Try this:

<script type="text/javascript">
$.fn.toggleFuncs = function() {
    var functions = Array.prototype.slice.call(arguments),
    _this = this.click(function(){
        var i = _this.data('func_count') || 0;
        functions[i%functions.length]();
        _this.data('func_count', i+1);
    });
}
$('$showmenu').toggleFuncs(
        function() {
           $( ".menu" ).toggle( "drop" );
            },
            function() {
                $( ".menu" ).toggle( "drop" );
            }
); 

</script>

First fuction is an alternative to JQuery deprecated toggle :) . Works good with JQuery 2.0.3 and JQuery UI 1.10.3


I would do something like this

DEMO in JsBin: http://jsbin.com/ofiqur/1/

  <a href="#" id="showmenu">Click Here</a>
  <div class="menu">
    <ul>
      <li><a href="#">Button 1</a></li>
      <li><a href="#">Button 2</a></li>
      <li><a href="#">Button 3</a></li>
    </ul>
  </div>

and in jQuery as simple as

var min = "-100px", // remember to set in css the same value
    max = "0px";

$(function() {
  $("#showmenu").click(function() {

    if($(".menu").css("marginLeft") == min) // is it left?
      $(".menu").animate({ marginLeft: max }); // move right
    else
      $(".menu").animate({ marginLeft: min }); // move left

  });
});

<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $(".click-header").click(function(){
            $(this).next(".hidden-content").slideToggle("slow");
            $(this).toggleClass("expanded-header");
        });
    });
</script>
.demo-container {
    margin:0 auto;
    width: 600px;
    text-align:center;
}
.click-header {
    padding: 5px 10px 5px 60px;
    background: url(images/arrow-down.png) no-repeat 50% 50%;
}
.expanded-header {
    padding: 5px 10px 5px 60px;
    background: url(images/arrow-up.png) no-repeat 50% 50%;
}
.hidden-content {
    display:none;
    border: 1px solid #d7dbd8;
    padding: 20px;
    text-align: center;
}
<div class="demo-container">
    <div class="click-header">&nbsp;</div>
    <div class="hidden-content">Lorem Ipsum.</div>
</div>

Use slideToggle(500) function with a duration in milliseconds for getting a better effect.

Sample Html

<body>
    <div class="growth-step js--growth-step">
        <div class="step-title">
            <div class="num">2.</div>
            <h3>How Can Aria Help Your Business</h3>
        </div>
        <div class="step-details ">
            <p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
                management organization with expertise. </p>
        </div>
    </div>
    <div class="growth-step js--growth-step">
        <div class="step-title">
            <div class="num">3.</div>
            <h3>How Can Aria Help Your Business</h3>
        </div>
        <div class="step-details">
            <p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
                management organization with expertise. </p>
        </div>
    </div>
</body>

In your js file, if you need child propagation for the animation then remove the second click event function and its codes.

$(document).ready(function(){
    $(".js--growth-step").click(function(event){
       $(this).children(".step-details").slideToggle(500);
         return false;
    });
//for stoping child to manipulate the animation
    $(".js--growth-step .step-details").click(function(event) {
        event.stopPropagation();
   });
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete

Examples related to jquery-effects

JQuery show and hide div on mouse click (animate)