How to save style inline in a variable?

0

I need to assign to some variable the inline style of a div, before it can be modified:

The example below is what I expect to happen, however I can not force 'top', '100px' on the second button but rather retrieve the original value that is inside the div's inline style box .

$('.top-1000').click(function(){
  $('.box').css('top','200px');
});

$('.back-100').click(function(){
  $('.box').css('top','100px');
});
body{
position:relative;
}
.box{
height:100px;
width:100px;
background:red;
position:absolute;
left:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="box" style="top: 100px;">

</div>

<button class="top-1000">Go</button>
<button class="back-100">Go back</button>
    
asked by anonymous 23.01.2018 / 18:33

1 answer

1

Of course, just save the property value you want before any changes, using the getter version of the css() :

var original_val = $('.box').css('top'); // <-- acrescentar isto
$('.top-1000').click(function(){
  $('.box').css('top','200px');
});

$('.back-100').click(function(){
  $('.box').css('top',original_val); // <-- repor original_val
});
body{
position:relative;
}
.box{
height:100px;
width:100px;
background:red;
position:absolute;
left:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="box" style="top: 100px;">

</div>

<button class="top-1000">Go</button>
<button class="back-100">Go back</button>
    
23.01.2018 / 18:39