0

I am trying to do a background color transition but have been stuck.

My goal is when a button is clicked, I want to transition a background that is half red on the left side and half blue on the right side to slide left and become full blue.

I have attempted it in this jfiddle but I am not sure what I am doing wrong. Any help would be appreciated. Thank you!

https://jsfiddle.net/8Lbw23rt/

HTML code:

<div class="colorChange">
        <p>test</p>
</div>

<button class="test-button" id="test" type="button">Change Color!</button>

CSS Code:

.colorChange {
  width:150px;
  height: 150px;
  padding: 11px 16px;
  text-align:center;
  float:left;
  background: linear-gradient(to right, red 50%, blue 50%);
  background-size: 100% 100%;
  background-position:left bottom;
  margin-left:10px;
  transition:all 2s ease;
  margin-right: 50px;
}

.test-button {
  height: 50px;
  width: 100px;
}

JS Code:

$(function() {
    $('#test').on('click', function() {
        $('.colorChange').css('background-position', 'right bottom');
    })
})
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
Gary Toms
  • 33
  • 1
  • 4

1 Answers1

0

Make the background large enough that half of it can cover the entire element, then just move it:

$(function() {
  $('#test').on('click', function() {
    $('.colorChange').css('background-position', 'right bottom');
  })
})
.colorChange {
  width: 150px;
  height: 150px;
  padding: 11px 16px;
  text-align: center;
  float: left;
  /* background: #ff3232; */
  background: linear-gradient(to right, red 50%, blue 50%);
  background-size: 200%;
  background-position: center bottom;
  margin-left: 10px;
  transition: all 2s ease;
  margin-right: 50px;
}

.test-button {
  height: 50px;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="colorChange">
  <p>test</p>
</div>

<button class="test-button" id="test" type="button">Change Color!</button>

Fiddle

isherwood
  • 58,414
  • 16
  • 114
  • 157