Im trying to create a HEX code generator and display it on a heading but the problem is it doesnt overwrite the text inside the heading instead it only placed adjacent to it.
let hexGenerator = {
result: '',
characters: 'ABCDEF0123456789',
hexColor: function() {
for (let i = 0; i < 6; i++) {
this.result += this.characters.charAt(Math.floor(Math.random() * this.characters.length));
}
return this.result;
}
}
window.onload = () => {
document.querySelector('button').addEventListener('click', () => {
document.getElementById('demo').innerHTML = 'HEX VALUE: #' + hexGenerator.hexColor();
})
}
<body>
<h1 id="demo">HEX VALUE: #</h1>
<button>Click Me!</button>
</body>
element.innerHTML = ... does overwrite.
result += ... does not overwrite.
Thanks for providing a minimum example. Add a this.result = '' will reset the value for each click.
let hexGenerator = {
result: '',
characters: 'ABCDEF0123456789',
hexColor: function() {
this.result = '';
for (let i = 0; i < 6; i++) {
this.result += this.characters.charAt(Math.floor(Math.random() * this.characters.length));
}
return this.result;
}
}
window.onload = () => {
document.querySelector('button').addEventListener('click', () => {
document.getElementById('demo').innerHTML = 'HEX VALUE: #' + hexGenerator.hexColor();
})
}
<body>
<h1 id="demo">HEX VALUE: #</h1>
<button>Click Me!</button>
</body>
That being said, there's no reason to create a hexGenerator object here. You could just use a simple function:
let hexColor = () => {
let characters = 'ABCDEF0123456789';
let result = '';
for (let i = 0; i < 6; i++)
result += characters.charAt(Math.floor(Math.random() * characters.length));
return result;
};
window.addEventListener('load', () =>
document.querySelector('button').addEventListener('click', () =>
document.getElementById('demo').textContent = 'HEX VALUE: #' + hexColor()));
<body>
<h1 id="demo">HEX VALUE: #</h1>
<button>Click Me!</button>
</body>
Edit:: per comment, here's how you'd do this with classes:
class Generator {
constructor() {
this.characters = 'ABCDEF0123456789';
}
hexColor() {
let result = '';
for (let i = 0; i < 6; i++)
result += this.characters.charAt(Math.floor(Math.random() * this.characters.length));
return result;
}
}
let gen = new Generator();
window.addEventListener('load', () =>
document.querySelector('button').addEventListener('click', () =>
document.getElementById('demo').textContent = 'HEX VALUE: #' + gen.hexColor()));
<body>
<h1 id="demo">HEX VALUE: #</h1>
<button>Click Me!</button>
</body>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With