Philip Savenok Philip Savenok - 1 day ago 4
Javascript Question

toggle function that gradientifies background color

Basically I'm trying to toggle a function that gradually change background color of div. There's a separate script.js file that is responsible for function gradientify() to run.

I'm just not sure what is the logic to toggle a function...

index.html

<body>
<button type="button" id="btn"></button>
<div style="width: 100px; height: 100px;"></div>
</body>


script.js

$('#btn').click(function() {
$('div').toggle(function() {
$(this).gradientify({
gradients: [
{ start: [49,76,172], stop: [242,159,191] },
{ start: [255,103,69], stop: [240,154,241] },
{ start: [33,229,241], stop: [235,236,117] }
]
});
});
});

Answer

The Jquery toggle function toggles the visibility of an element. It basically sets the css property display to display: none. If you want the content inside the "gradientifyied" element to still be visible when you toggle the gradients then you can't use Jquery.toggle.

Sadly the gradientify API doesn't provide any way to cancel the gradients once they are set on an element so the only way to toggle the gradients on an element is to remove it from the DOM all together.

We can create a copy of the clean element before the gradiants are applied and when we want to remove the gradients, we remove the old element from the DOM and insert the copy we kept.

function toggleGradients() {
  var gradientTargetCopy = $( ".gradientTarget" ).clone()
  var gradientsOff = true;
  return function() {
    if (gradientsOff) {
      $('.gradientTarget').gradientify({
        gradients: [
          { start: [49,76,172], stop: [242,159,191] },
          { start: [255,103,69], stop: [240,154,241] },
          { start: [33,229,241], stop: [235,236,117] }
        ]
      });
    } else {
      $('.gradientTarget').remove()
      $('body').append(gradientTargetCopy)
      gradientTargetCopy = $( ".gradientTarget" ).clone()
    }
    gradientsOff = !gradientsOff
  }
}

$('#btn').click(toggleGradients());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://codefog.github.io/jquery-gradientify/jquery.gradientify.min.js"></script>

<body>
    <button type="button" id="btn">Toggle gradients</button>
    <div class="gradientTarget" style="width: 100px; height: 100px;">Hello!</div>
</body>

Comments