Exchange text from the title element with html and javascript

Asked

Viewed 38 times

-3

I have the following title:

<h1>LANÇAMENTO: <span class="verde">PS5</span> E <span class="verde">XBOX SERIE S</span></h1>

In css I change the color of the span part. I have the following javascript function to change the text:

function trocaTituto(){
  var titulo = $('.hero h1')
  var textos = ["CONFIRA NOSSAS NOVIDADES", "LANÇAMENTO: PS5 E XBOX SERIE S"]
  let position = 0
    setInterval(() => {
      //efeito de desaparecer
      $(titulo).fadeOut(function() {

      //função "callback" que mostra o próximo texto
      if (position >= textos.length) position = 0;
      $(titulo).text(textos[position++]).fadeIn();
      });

    }, 5000);
}

How do I put the green text back to the first part?

1 answer

-3


Would it be close to the code below? Voce can add the span tag next to the text, and change the function text() to html() so you can recognize text together with html and change the colors.

function trocaTituto(){
  var titulo = $('.hero h1')
  var textos = ["CONFIRA NOSSAS NOVIDADES", `LANÇAMENTO: <span class='verde'>PS5</span> E <span class='verde'>XBOX SERIE S</span>`]
  
  let position = 0
    setInterval(() => {
      //efeito de desaparecer
      $(titulo).fadeOut(function() {

      //função "callback" que mostra o próximo texto
      if (position >= textos.length) position = 0;
      
      $(titulo).html(textos[position++]).fadeIn();
      }); 
     

    }, 1000);
}
.verde{
 color: green; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="banner" id="banner"> 
 <section class="hero section"> 
  <h1> LANÇAMENTO: 
    <span id="verde1" class="verde">PS5</span> E <span id="verde2" class="verde">XBOX SERIES S</span> 
  </h1> <a href="#historia" class="btn-banner">Saiba mais</a> 
 </section> 
</div>
<button onclick='trocaTituto()'>trocar</button>

  • I have an H1 with some span inside, so some words will be white and others green. This function keeps alternating the text of this H1, but I can’t get it to switch with words of different colors, or it turns all white or all green.

  • can you share html code? that then I can help you better

  • That’s it here <div class="banner" id="banner"> <Section class="Hero Section"> <H1> RELEASE: <span id="verde1" class="green">PS5</span> E <span id="Verde2" class="green">XBOX SERIES S</span> </H1> <a href="#historia" class="btn-banner">Learn more</a> </Section> </div>

  • in case I change this H1, I can change the whole H1, but not the span that make some words stay of other colors

Browser other questions tagged

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