0

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>
4
  • 1
    add running snippet of code. Commented Jun 22, 2020 at 11:12
  • What browser are you using ? Commented Jun 22, 2020 at 11:12
  • this code not giving any issue. add your css also in snippet Commented Jun 22, 2020 at 11:17
  • @Cid both chrome and firefox Commented Jun 22, 2020 at 11:24

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

2

you need to do

<a href="javascript:void(0)"

javascript:void is an incomplete statement, that's why you run into problems here.

2 Comments

void is an operator, not a function.
that's true, but still: stackoverflow.com/questions/1291942/… - you could write "void 0" as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.