Forrest Dimond
Forrest Dimond

Reputation: 1

How do I create an If Else condition based on margin styles

I'm having difficulty making this animation come to fruition upon a click with an If Else condition within it. So the #joinbox starts at "margin-top" of 7%, I want it to move on a click from #paper4 to a "margin-top" of -19%; only if it's already at 7% though. If not, I'd like it to move back to 7% upon the click. Also, I'm using the velocity js which is just a smoother .animate function.

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

    if ($("#joinbox").css("margin-top")=="7%") 
        {$("#joinbox").velocity({"margin-top": "-19%"}, 200, "easeInOutQuad");}

         else {$("#joinbox").velocity({"margin-top": "7%"}, 200, "easeInOutQuad");}
});

Here is the original style of #joinbox

#joinbox {
    margin-top: 7%;
    margin-left: 31.5%;
    width: 35%;
    position: fixed;
    box-shadow: 0 5px 10px #332E2C;
    background-color: white;
    padding: 1%;
}

Upvotes: 0

Views: 472

Answers (2)

Joel Almeida
Joel Almeida

Reputation: 8037

Since you will only retrieve the value in px. You can use the parent width and calculate the % by hand.

Something like this:

$("#paper4").click(function() {
    var elementMargin = parseInt($('#joinbox').css('margin-top')),
        parentWidth = Math.round($('#joinbox').parent().width() * 0.07);
    
    if(elementMargin === parentWidth) {
    	console.log('margin-top: 7%')
    } else {
    	console.log('margin-top: -19%')
    }
});
#joinbox {
    margin-top: 7%;
    margin-left: 31.5%;
    width: 300px;
    height: 100px;
    background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="joinbox">
    
    
</div>

<button id="paper4">Hay</button>

Upvotes: 0

jack blank
jack blank

Reputation: 5195

According to my memory .css("margin-top") returns something in pxlike 7px not percent like 7% so maybe try converting the percentage to px. you could use something like $().offset for conversion.

Try doing console.log($("#joinbox").css("margin-top")) you wont get percentage I think.

Upvotes: 2

Related Questions