How to save inline style in a variable?

Asked

Viewed 102 times

0

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

The example below is what I hope will happen, but I cannot force 'top', '100px' on the second button and recover the original value that is inside the inline style of the div box 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>
<div class="box" style="top: 100px;">

</div>

<button class="top-1000">Go</button>
<button class="back-100">Go back</button>

  • I don’t quite understand, can explain a little more?

1 answer

1


Of course, just save the value of the property you want before any change, using the version getter of the method 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>
<div class="box" style="top: 100px;">

</div>

<button class="top-1000">Go</button>
<button class="back-100">Go back</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.