0

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>
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175

5 Answers5

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>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
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>```
Mahesh T.
  • 61
  • 5
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>
0stone0
  • 34,288
  • 4
  • 39
  • 64
0

Your code has some issues, already mentioned by other answers.

It is generally not a good idea to use inline event handlers.

Here is a snippet using event delegation, and without jQuery. It's using the function randomColor to create random colors per letter.

document.addEventListener(`click`, handle);
let to = 0;
const randomColor = _ => `rgb(${[0, 0, 0]
    .map( _ => Math.floor(Math.random() * 255)).join(`,`)})`;

function colorize(value) {
  const result = document.querySelector(`#result`);
  const colorized = [...value].map(val =>
    `<span style="color:${randomColor()}">${val}</span>`);
  result.textContent = ``;
  result.insertAdjacentHTML(`beforeend`, colorized.join(``));
  to = setTimeout(_ => colorize(value), 1000);
}

function handle(evt) {
  if (evt.target.id === `colorize`) {
    const value = document.querySelector(`#text`).value.trim();
    
    if (value) {
      clearTimeout(to);
      document.querySelector(`#text`).value = ``;
      return colorize(value);
    }
  }
  
  return true;
}
#result {
  font-weight: bold;
  letter-spacing: 0.5em;
}
<input type="text" name="text" id="text" 
  value="TEST ME NOW", placeholder="enter some text">
<button id="colorize">ENTER</button>
<p id="result"></p>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

First, I have separated the randomize function, because you need it both at the setInterval and separately. setInterval does the change upon every second, but it waits for a second before doing it for the first time. Since we want the word to be shown instantly, we call it separately as well. Second, when you call a function, you need to call it by name in most cases (I will not go into describing the exceptions from this rule here for the sake of simplicity) and function is a reserved word. Thirdly, the jQuery load event that you defined is executed when the load event is triggered, instead you want a click event. Fourthly, variables are not functions. I may have fixed other issues as well in your code that I no longer remember. Feel free to ask any questions.

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

    function randomize(div, chars) {
        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);
        }
    }
    function doIt() {
        var div = $('#arch'); 
        var text = document.getElementById('text').value;
        var chars = text.split('');
        randomize(div, chars);
        setInterval(function() {
            randomize(div, chars);
        }, 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="doIt()">ENTER</button>
    <br /><br />
    <div id="arch"></div>
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175