Home > Enterprise >  Change a color of a text line when clicked with JS
Change a color of a text line when clicked with JS

Time:09-25

I am new into JavaScript and I've been trying to change the color of a text line in my website when I click on it with JS, I know there are ways to do it just with CSS but I'd like to practice some JS, this is what I've been trying so far:

I have this list:

function white() {
  const input = document.getElementById("weekly");
  input.style.color = "white";
}
<ul>
  <li><a id="weekly" href="/index.html" onclick="white()">Weekly</a></li>
</ul>

It is a longer list but i didn't want this to look messy :)

I want to change the color of "Weekly" when it's clicked on and this is what i have tried: I've been trying for a while and this is the best I came up with but doesn't seem to work.

CodePudding user response:

Although only for a split second, the anchor tag's text is indeed styled to be rendered as white text. Your anchor tag takes the user to /index.html and thus the effect is not visible for as long as the user is on the page. To avoid redirecting, set the href attribute to #:

  function white() {
    const input = document.getElementById("weekly");
    input.style.color = "white";
  }
<ul>
  <li><a id="weekly" href="#" onclick="white()">Weekly</a></li>
</ul>

CodePudding user response:

Your very same code snippet works. The issue you are facing is that your <a> tag has a link, that is navigating to what I assume the same page, hence the page is reloaded and the link is black again. See withoud the href (and a more visible color):

function white() {
  const input = document.getElementById("weekly");
  input.style.color = "green";
}
<ul>
  <li><a id="weekly" onclick="white()">Weekly</a></li>
</ul>

CodePudding user response:

Your snippet works fine, but might make it a little more generic so you can use it in other ways, as example below.

// es6 "fat arrow" one liner
changeColor = (element, color) => element.style.color = color;

// maybe more familiar
// function changeColor(element, color) {
//  element.style.color = color;
// }
<ul>
  <li><a id="weekly" href="#" onclick="changeColor(this, 'red')">Weekly</a></li>
  <li><a id="daily" href="#" onclick="changeColor(this, 'blue')">Daily</a></li>
  <li><a id="hourly" href="#" onclick="changeColor(this, 'green')">Hourly</a></li>
</ul>

CodePudding user response:

normally <a> tags redirect you to a link but you can avoid redirection and then apply custom function to <a> tag by using preventDafault function which will stop default behaviour of an element

function white(event) {
  event.preventDefault()
  const input = document.getElementById("weekly");
  input.style.color = "white";
}
<ul>
  <li><a id="weekly" href="/index.html" onclick="white(event,this)">Weekly</a></li>
</ul>

  • Related