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>
CodePudding user response:
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>
CodePudding user response:
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>```
CodePudding user response:
There are a few issues with your code.
functionis preserved keyword, name your function something else- You're getting the contets of
archbefore there's something in it. I now filltextusing the input field - The
forshould be inside thesetInterval - Clearing
archshould 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>
CodePudding user response:
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>
CodePudding user response:
several points can be modified to have a working function :
your function should be name with a true name (in my sample loadChangeColor)
the changing of character color should be a function call in interval
you don't have to clear the html of #arch each second just change css color apply
var colours = ['#000000', '#FF0000', '#990066', '#FF9966', '#996666', '#00FF00', '#CC9933' ], idx;
function changeEachCharColor() {
$('#arch span').each((i, char) => {
idx = Math.floor(Math.random() * colours.length);
$(char).css("color", colours[idx]);
})
}
function loadChangeColours(delay) {
$('#arch').html(
$('#text').val().split('').map(char => `<span>${char}</span>`)
);
setInterval(changeEachCharColor, delay);
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<input type="text" name="text" id="text">
<button onclick="loadChangeColours(1000)">ENTER</button>
<br /><br />
<div id="arch"></div>
CodePudding user response:
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`);
// remove old value
result.textContent = ``;
// create spans with random color from the input value
const colorized = [...value].map(val =>
`<span style="color:${randomColor()}">${val}</span>`);
// fill div#result with the spans
result.insertAdjacentHTML(`beforeend`, colorized.join(``));
// (re)set the timeout. [to] is necessary to be able to
// cancel the timeout
to = setTimeout(_ => colorize(value), 1000);
}
function handle(evt) {
if (evt.target.id === `colorize`) {
const value = document.querySelector(`#text`).value.trim();
if (value) {
// stop running timeout if applicable
clearTimeout(to);
// empty the text field
document.querySelector(`#text`).value = ``;
// start coloring
return colorize(value);
}
}
// no value: do nothing
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>
