skip to Main Content

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

3

Answers


  1. 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>
    Login or Signup to reply.
  2. <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.

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search