Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
Change color of letters every second from user textbox input

I have to write a page where user types some text into a textbox. User clicks the enter button, after this, the text written into the textbox is shown under the textbox. Every letter from the text under textbox should change its color every one second.

I don't know how can I refer to this jQuery function $(function() {} ) because console gives me error that I have to specify the name of the function. I'm just a beginner at programming and I would be very grateful for any kind of help.

var colours = ["#000000", "#FF0000", "#990066", "#FF9966", "#996666", "#00FF00", "#CC9933"], 
        idx;    

    $(function() {
        var div = $('#arch'); 
        var chars = div.text().split('');
        var text = document.getElementById('text').value;
        document.getElementById('arch').innerHTML = text;
        div.html('');     
        for(var i = 0; i < chars.length; i++) {
            idx = Math.floor(Math.random() * colours.length);
            var span = $('<span>' + chars[i] + '</span>').css("color", colours[idx]);
            div.append(span);
            chars.setInterval(colours, 1000); // change colors of letters every second
        }

    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="text" id="text">
    <button onclick="function()">ENTER</button>
    <br /><br />
    <div id="arch"></div>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The main issue in your code is because you've not defined the function() you invoke from the onclick attribute anywhere. However it should be noted that using onX attributes in HTML to invoke JS functions is outdated and no longer good practice.

The better approach is to use unobtrusive event handlers bound through JS, either using the native addEventListener() method or jQuery's on() method, as you've included that library.

From there you can define your logic to set the text of the #arch element based on the input value, and then create a separate function, called in setInterval() every 1 second, to loop through the span elements and change their colour randomly. Try this:

let colours = ["#000000", "#FF0000", "#990066", "#FF9966", "#996666", "#00FF00", "#CC9933"];

jQuery($ => {
  $('button').on('click', () => {
    let text = $('#text').val();
    let $arch = $('#arch').html('');

    $arch.append(text.split('').map(char => `<span>${char}</span>`));
    updateColours(); // set random colours now
    setInterval(updateColours, 1000); // update colours every second
  });
  
  let updateColours = () => {
    $('#arch span').each((i, el) => {
      let idx = Math.floor(Math.random() * colours.length);
      $(el).css("color", colours[idx])
    });
  }
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<input type="text" name="text" id="text" value="Lorem ipsum dolor sit amet consectetur adipiscing elit" />
<button>ENTER</button>
<br /><br />
<div id="arch"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

I have resolved the error you can check this code

<html>

<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>

    <input type="text" name="text" id="text">
    <button>ENTER</button>
    <br /><br />
    <div id="arch"></div>

    <script>

        var colours = ["#000000", "#FF0000", "#990066", "#FF9966", "#996666", "#00FF00", "#CC9933"],
            idx;

        $(function () {

            $("button").click(function () {
                console.log("button clicked");
                var text = document.getElementById('text').value;
                document.getElementById('arch').innerHTML = text;
                var div = $('#arch');
                var chars = div.text().split('');


                setInterval(
                    function () {
                        div.html('');
                        for (var i = 0; i < chars.length; i++) {
                            idx = Math.floor(Math.random() * colours.length);
                            var span = $('<span>' + chars[i] + '</span>').css("color", colours[idx]);
                            div.append(span);

                        }
                    }, 1000); // change colors of letters every second

            });
        });
    </script>
</body>

</html>```
about 4 years ago · Juan Pablo Isaza Relatório

0

There are a few issues with your code.

  1. function is preserved keyword, name your function something else
  2. You're getting the contets of arch before there's something in it. I now fill text using the input field
  3. The for should be inside the setInterval
  4. Clearing arch should be inside the setInterval

var colours = ["#000000", "#FF0000", "#990066", "#FF9966", "#996666", "#00FF00", "#CC9933"];
var idx;    

function showLetters() {
    var ele = $('#arch'); 
    var chars = document.getElementById('text').value.split('');
    
    setInterval(function() {
      ele.empty();
      for(var i = 0; i < chars.length; i++) {
          idx = Math.floor(Math.random() * colours.length);
          var span = $('<span>' + chars[i] + '</span>').css("color", colours[idx]);
          ele.append(span);
      }
    }, 1000);   
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="text" id="text">
<button onclick="showLetters()">ENTER</button>
<br /><br />
<div id="arch"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda