Hussain Khalil
Hussain Khalil

Reputation: 1650

No result when animating styles in JQuery

I'm using the following code to animate the margin-top CSS style of a div with an id of "div".

HTML:

<div id="div">
    <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </p>
    <button id="trigger">
        Change Margin
    </button>
</div>

Javascript (In the head section):

<script type="text/javascript" src="scripts/jquery-1.11.0.min.js"></script>
<script>
$("trigger").mouseup(function() {
    $("div").animate({
        marginTop: "-20px"
    });
});
</script>

However, when I click the button, nothing happens... Why is that?

JSFiddle: http://jsfiddle.net/zLx5U/

Upvotes: 1

Views: 40

Answers (2)

Tiago Marinho
Tiago Marinho

Reputation: 2216

First, as said in other answers, your code is missing # inside the jQuery element selector.

Also, I highly recommend avoiding javascript animations: Use CSS transitions when possible, it's less buggy and easier to manipulate. Here's @Pdk1303's fiddle modified to use CSS transitions and class toggling, so if you click the button twice the margin will return to the default.

JavaScript:

$(document).ready(function(){
    $("#trigger").on("click", function(){
        $("div").toggleClass("lessMargin");
    });
});

Upvotes: 1

Pbk1303
Pbk1303

Reputation: 3802

1)trigger is an id ,your missing '#' in your jquery code.
2) wrap your jquery code in document.ready.

$(document).ready(function(){
$("#trigger").mouseup(function() {
    $("div").animate({
        marginTop: "-20px"
    });
});
});

Please see this fiddle.

Upvotes: 2

Related Questions