Vera Perrone Vera Perrone - 1 year ago 40
Javascript Question

How to add more margin on top of the old one using jquery?

The title says it all, how can I add more margin on top of the old one? So lets say I have this var:

var playerPossition = $('#player').css('margin-top')
its current margin is 375px, lets say I want to make it 275px how could I accomplish this? Thanks for your time!

Answer Source

First you need to get the magin-top into a number that you can do math on

    //This returns a string "375px" we need to isolate the number
    var margin_height = $('#player').css('margin-top');
    //.split will turn the string into an array breaking on the parameter
    //"375px" becomes ["375", "x"];
    var margin_top = margin_height.split("p");
    //Now we just need to grab the number from the array
    margin_top = margin_top[0]

Then you will need to subtract your number

    margin_top -= 100;

And finally change the margin-top to the desired amount

    $('#player').css('margin-top', margin_top);