hobbywebsite
hobbywebsite

Reputation: 143

javascript get style and increment

I'm trying to make a slider that changes the margin-left attribute in the external css onclick. So I need to get the attribute and then set the new attribute.

here is my code:

<style>
#divName
 {
  margin-left:20px;
 }
</style>

    <script language="javascript" type="text/javascript">  

                var x = document.getElementById(divName);

            if (x.currentStyle)
            {
                var y = x.currentStyle[marginLeft];
            }
            else (window.getComputedStyle)
            {
                var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(marginLeft);
            }

                y = y + 20;

                document.getElementById(divName).style.marginLeft = y .'px';

    </script>

thanks for your time

Upvotes: 0

Views: 553

Answers (1)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262919

In Javascript, the . operator does not concatenate strings.

Use the + operator instead:

document.getElementById(divName).style.marginLeft = y + 'px';

You also probably need to pass marginLeft as a string, not a name (unless there is a variable in scope that is named marginLeft and set to "marginLeft"):

var y = x.currentStyle["marginLeft"];

And:

var y = document.defaultView.getComputedStyle(x, null).getPropertyValue("marginLeft");

Upvotes: 1

Related Questions