-2

How to change the color of the text after clicking on it in Squarespace?

Where in the code do I insert the block id to target a particular block?

Here is the code I was trying to use

<script>

    document.getElementById('change').onclick = changeColor;   

    function changeColor() {
        document.body.style.color = "purple";
        return false;
    }   

</script>

I need some help with JavaScript

Behemoth
  • 5,389
  • 4
  • 16
  • 40

3 Answers3

0

You need to apply the CSS on the DOM element you want to style not on the document.body.

Just as a side note, nowadays it's preferred to use an eventlistener for things like this since it doesn't completely override a property of an element. (onclick in this case)

const element = document.getElementById('change');

function changeColor() {
  element.style.color = "purple";
}

element.onclick = changeColor;

// or
// element.addEventListener("click", changeColor);
<p id="change">This should change onclick</p>
Behemoth
  • 5,389
  • 4
  • 16
  • 40
0
<div id="foo"></div>

document.getElementById("foo").onclick = funciton {changeColor()};

function changeColor(){
    document.getElementById("foo").style.color = "#00ff00";
}

you can change "foo" to anything you want but it needs to be unique.

Eren
  • 36
  • 6
  • 1
    Is this the way code would look like with the block id and color inserted?
    document.getElementById("#block-87bb744eebfb16c3f9ad").onclick = funciton {changeColor()}; function changeColor(){ document.getElementById("#block-87bb744eebfb16c3f9ad").style.color = "#bfafa6"; }
    – Oleksii Ivanenko Aug 08 '23 at 16:39
0

Put the ID of the CSS selector you're targeting as an attribute in the HTML element.

<html>
  <body>
    <p id="para">Some text here</p>
    <button onclick="changeColor('blue');">blue</button>
    <button onclick="changeColor('red');">red</button>
  </body>
</html>

Within the java script it would be like this

function changeColor(newColor) {
  const elem = document.getElementById("para");
  elem.style.color = newColor;
}

Source: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

Isham7920
  • 11
  • 4