Reputation: 23
I Have this code where i keep getting the same error after trying everything. I have also checked other similar stackoverflow question but still no answer worked please can you help me out
ERROR: Uncaught SyntaxError: Unexpected end of input
Javascript
const colors = document.getElementsByClassName('s-colors');
for(var i = 0; i < colors.length; i++) {
colors[i].addEventListener('click', () => {
console.log(this.getAttribute("data-color"));
})
}
Html
<div class="pdt-color">
<h4>Color</h4>
<div class="colors">
<a href="javascript:void" class="s-colors" data-color="red"
style="background-color: red;"></a>
<a href="javascript:void" class="s-colors" data-color="black"
style="background-color: black;"></a>
<a href="javascript:void" class="s-colors" data-color="yellow"
style="background-color: yellow;"></a>
<a href="javascript:void" class="s-colors" data-color="blue"
style="background-color: blue;"></a>
</div>
</div>
Upvotes: 0
Views: 474
Reputation: 31
The code below should do the trick. I replaced the javascript links with # links and prevent the URL from changing on click by using the preventDefault function. Give it a try.
const colors = document.querySelectorAll('.s-colors');
colors.forEach(color => {
color.addEventListener('click', (e) => {
e.preventDefault();
console.log(color.dataset.color);
});
});
.s-colors {
width: 100px;
height: 50px;
display: inline-block;
}
<h4>Color</h4>
<a href="#" class="s-colors" data-color="red" style="background-color: red;"></a>
<a href="#" class="s-colors" data-color="black" style="background-color: black;"></a>
<a href="#" class="s-colors" data-color="yellow" style="background-color: yellow;"></a>
<a href="#" class="s-colors" data-color="blue" style="background-color: blue;"></a>
Upvotes: 3
Reputation: 1176
you need to do
<a href="javascript:void(0)"
javascript:void is an incomplete statement, that's why you run into problems here.
Upvotes: 2