I'm aiming for a prompt with a new line.
Guess a number:
> __
//instead of
Guess a number: __
I'm looking for something to do this, adding a \n in the prompt like below causes the prompt have issues.
example = prompt("Guess a number \n >")
Is this possible?
You can't change the position of the prompt
's input area from taking up the entire line at the bottom of the popup.
But you can, if you create a proper modal instead. (prompt
and its cousins are quite user-unfriendly anyway - best to avoid them if possible) Maybe do something like this:
const makePopup = (text, callback) => {
const modal = document.body.appendChild(document.createElement('div'));
modal.innerHTML = text + '<input style="margin-left: 20px">';
const input = modal.children[0];
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
modal.remove();
callback(input.value);
}
});
};
makePopup('foo', (value) => {
console.log('Got value', value);
});
If you want to have multiple popups, it might be easier to make them Promise-based, and then you can await
each call, to kind of simulate the blocking effects of prompt
:
const makePopup = (text) => {
return new Promise((resolve) => {
const modal = document.body.appendChild(document.createElement('div'));
modal.innerHTML = text + '<input style="margin-left: 20px">';
const input = modal.children[0];
input.focus();
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
modal.remove();
resolve(input.value);
}
});
});
};
(async () => {
const num = Math.floor(Math.random() * 5);
let guessedNum;
do {
guessedNum = await makePopup('Guess a number 0-4');
} while (Number(guessedNum) !== num);
console.log('You Win');
})();