Justin D.
Justin D.

Reputation: 4976

Javascript display onclick with an animation

I want to animate a simple search form. Before the click event, it is hidden behind my fix nav bar (margin-top:-47px). When the user clicks a search button, I want to set the form's margin-top property to 0px so it shows on the page.

jsFiddle

I am using this HTML :

<nav>
  <a data-icon="search" class="search-form-toggle"></a>

...
<div class="form search-form">
                <fieldset data-icon="search">
                    <input type="search" placeholder="Search...">
                </fieldset>
            </div>

And this CSS :

.search-form {
    margin-top: -47px;
}

And the following javascript (jQuery) :

$('.search-form-toggle').click(function(){
    if($(".search-form").css("margin-top") == "-47px") {
        $(".search-form").animate({margin-top: "0px"}, 1000);
    } else {
        $(".search-form").animate({margin-top: "-47px"}, 1000);
    }
    return false;
});

When I click the button, it is not working... I guess it is a Javascript issue?

Plus, can I achieve the same result (nice transition) without using jQuery?

Upvotes: 0

Views: 2233

Answers (3)

Justin D.
Justin D.

Reputation: 4976

The answer given were really helpful in debugging my code. However, I went with another option when I found animte.css. It is a CSS library that provides multiple animations for divs and others.

I was also using QuoJS, and I didn't want to add jQuery to my loading time, especially since I am developing for mobile devices.

Here is my final code :

JS :

document.querySelector(".search-toggle").addEventListener("click", function(){ var form = $$(".search-form");

if (form.hasClass('display')) {
    form.removeClass('display');
} else {
    form.addClass('display animated flipInX');
}

});

CSS :

.search-form {
    display:none;
}

.display {
    display:block;
}

At first, my div only have the .search-form class, so it is not displayed. I add the .display class with QuoJs with the addClass() function.

The transition are very sleek, thanks to animate.css.

Upvotes: 0

Hive7
Hive7

Reputation: 215

The error is in the .animate() it should be:

$(".search-form").animate({'margin-top' : '0px'}, 1000);

and

$(".search-form").animate({margin-top: "-47px"}, 1000);

You forgot the quotes around the margin-top

here's my working fiddle though make sure you add the ajax file that is attached

Fiddle

Upvotes: 2

reggaemahn
reggaemahn

Reputation: 6648

Here is the working fiddle. You'd forgot to put the quotes.

.animate({"margin-top": "XXpx"});

http://jsfiddle.net/5xxWu/

Upvotes: 1

Related Questions