Click on button to toggle display of another div

时间:2016-04-04 16:33:43

标签: javascript jquery html

I have a code that works perfectly to move elements from top, left, right or bottom sides, but seems to be, that it doesn't work with display property, here's my javascript code:

$('#icon-for-search').click(function () {
    var targetValue;

    if ($('#search-wrapper').css('top') == "0px") {
        targetValue = '55px';
    } else {
        targetValue = '0px';
    }

    $("#search-wrapper").animate({
        top: targetValue
        }, 500);
    });

I have a button with an id called "icon-for-search" and it toggles perfectly the top value of the #search-wrapper if it's clicked, but if I change it to display: block / none it doesn't work. Any particular reason? could someone explain me?

$('#icon-for-search').click(function () {
    var targetValue;

    if ($('#search-wrapper').css('display') == "none") {
        targetValue = 'block';
    } else {
        targetValue = 'none';
    }

    $("#search-wrapper").animate({
        display: targetValue
        }, 500);
    });

1 个答案:

答案 0 :(得分:1)

jQuery.animate works only with numeric CSS properties. You can just toggle element:

$('#icon-for-search').click(function () {
    $('#search-wrapper').fadeToggle('slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="icon-for-search">Search Icon</div>
<div id="search-wrapper">Search Wrapper</div>