Home > OS >  Trying to use jQuery to change background url but it's removing the -webkit-background-clip:tex
Trying to use jQuery to change background url but it's removing the -webkit-background-clip:tex

Time:12-16

I am trying to use jQuery to switch the background url. But when the jQuery kicks in and switches the URL, it removes the -webkit-background-clip:text; effect. Is it possible to do something so we can switch the background image but keep the clip text effect?

jQuery(function($) {
  var whatToSwitch = $('.homepage_overlaytext h1');
  var backgrounds = ['url(http://static.jsbin.com/images/jsbin_static.png)', 'url(http://static.jsbin.com/images/popout.png)'];
  var current = 0;

  function nextBackground() {
    whatToSwitch.css(
      'background',
      backgrounds[current =   current % backgrounds.length]
    );

    setTimeout(nextBackground, 5000);
  }
  setTimeout(nextBackground, 5000);
  whatToSwitch.css('background', backgrounds[0]);
});
h1 {
  background-size: contain;
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
  -webkit-text-fill-color: transparent;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <h3>
    Header 3
  </h3>
  <h1 style="background: url(&quot;http://static.jsbin.com/images/popout.png&quot;);">
    Header 1
  </h1>
  <p>
    Text
  </p>
</div>

I tried both background and background-image but it still removes the clipping effect.

CodePudding user response:

In your HTML (the inline CSS part where you applied the background-property), you used background instead of background-image. Just change the property and you can use jQuery to append the background-image you want.

jQuery(function($) {
  var whatToSwitch = $('.homepage_overlaytext h1');
  var backgrounds = ['url(http://static.jsbin.com/images/jsbin_static.png)', 'url(http://static.jsbin.com/images/popout.png)'];
  var current = 0;

  function nextBackground() {
    whatToSwitch.css(
      'background',
      backgrounds[current =   current % backgrounds.length]
    );

    setTimeout(nextBackground, 5000);
  }
  setTimeout(nextBackground, 5000);
  whatToSwitch.css('backgroundImage', backgrounds[0]);
});
h1 {
  background-size: contain;
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
  -webkit-text-fill-color: transparent;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <h3>
    Header 3
  </h3>
  <h1 style="background-image: url(&quot;http://static.jsbin.com/images/popout.png&quot;);">
    Header 1
  </h1>
  <p>
    Text
  </p>
</div>

  • Related