Javascript this change color

How to change the text color in JavaScript on button click

In this post, we will learn how to change the color of a text in JavaScript. We will create one small html-css-js project, that will contain only one button and clicking on that button will change the color of a text.

We need to change the color property of a component. In this example, we will change the color of a p or paragraph component.

Create one index.html file with the below content:

DOCTYPE html> html> head> title>Change Color in JStitle> head> body> button id="toBlue">Bluebutton> button id="toGreen">Greenbutton> button id="toRed">Redbutton> div> p id="output_text">Click the button to change the color.p> div> script> document.getElementById("toBlue").onclick = function ()  document.getElementById("output_text").style.color = 'blue'; > document.getElementById("toGreen").onclick = function ()  document.getElementById("output_text").style.color = 'green'; > document.getElementById("toRed").onclick = function ()  document.getElementById("output_text").style.color = '#FF0000'; > script> body> html>

Open this file in your favorite browser. It will show one text line with three buttons as like below:

js change text color

If you click on any of these buttons, it will change the color of the text.

  • The script tag holds the javascript part.
  • Each button has one id. All are different. Using document.getElementbyId in the JavaScript, we are accessing a specific button and we are adding one onclick listener. It means the function will be run if the user clicks on that element.
  • Now, inside the function, we are changing the color of the text. The text or p component also has one id. We are changing the style.color of the p component inside each function.
  • Each function invocation changes the color differently. We can pass the color names, or we can pass the hex value. Not all colors are defined, and the browser will not understand every name. So, it is a good practice to pass hexadecimal value instead of its name.

Источник

Javascript this change color

Для того, чтобы сделать сменяемость цвета с помощью javascript, при наведении мышки. Нам понадобится:

Нам понадобится элемент DOM div,

+ onmouseover — когда мышка будет попадать на элемент,

И когда мышка будет покидать элемент — onmouseleave и внутри функций, в зависимости от действия будем изменять цвет, или возвращать первоначальный:

example.onmouseleave = function() example.style.background= «yellow»;
>;

Результат замены цвета при наведении мышки на элемент:

Изменить цвет(background) нажав по элементу.

В этом пункте разберем замену background цвета по клику с расположением js кода внутри тега.

Для того, чтобы изменить цвет элемента нажав по нему, нам понадобится, как и в выше проведенном пункте:

Пусть это будет элемент DOM div,

Соберем это все в одн целое:

Результат замены цвета при клике на элемент:

Для того, чтобы увидеть изменение цвета элемента при нажатии на него нажмите по блоку!

Изменение цвета (background) javascript скриптом

Выше я уже рассмотрел один из вариантов изменения цвета (background) javascript внутри тега.

Теперь тоже самое(ну или похожее. ) сделаем внутри скрипта.

Стили для блока выделим в отдельный тег style

Далее скрипт изменения цвета (background) javascript скриптом

Используем один из способов onclick

Нам понадобится getElementById для получения объекта.

Ну и далее простое условие с проверкой, что внутри атрибута style , если цвет красный

Во всех други случаях, т.е. иначе(else) меняем на красный.

Скрипт javascript для замены background при нажатии

Не забываем. если не сделано onload, то скрипт должен находиться под выше приведенным кодом элемента, в котором собираемся изменить background при нажатии

if(if_id .style . background == «red»)

if_id .style . background = «#efefef»;

if_id .style . background = «red»;

Пример изменения background при нажатии javascript

Нам остается разместить приведенный код прямо здесь. Чтобы проверить как работает изменение background при нажатии javascript кликните по ниже идущему цветному блоку.

Изменение цвета кнопки (background) javascript

С помощью самописного скрипта, заставим кнопки менять цвет.

Алгоритм смены цвета кнопки.

У кнопки должно быть что-то одинаковое — «class» = click_me.

И что-то разное. уникальное, это id.

Получим имена класса и ид:

Условие -если нажали по нашей кнопке с классом:

Получаем объект из имени(которое получили раннее):

При покрашенной кнопке возвращаем нажатой кнопке её цвет по умолчанию:

Иначе, всем кнопкам с классом возвращаем в цикле её цвет по умолчанию и только той кнопке, по которой нажали изменяем цвет::

else
var links = document.querySelectorAll(«.click_me»);
links.forEach(link => link.setAttribute(«style», «background:#efefef»);
>)
if_id .style . background = «red»;
>

Соберем весь код смены цвета с помощью javascript

the_class = e . target.className;

if(if_id .style . background == «red»)

if_id .style . background = «#efefef»;

var links = document.querySelectorAll(«.click_me»);

if_id .style . background = «red»;

Источник

Javascript this change color

Last updated: Jul 25, 2022
Reading time · 3 min

banner

# Table of Contents

# Change a Button’s color onClick in JavaScript

To change a button’s color onClick:

  1. Add a click event listener to the button.
  2. Each time the button is clicked, set its style.backgroundColor property to a new value.
  3. Optionally set its style.color property.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> button id="btn">Buttonbutton> script src="index.js"> script> body> html>

And here is the related JavaScript.

Copied!
const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick() btn.style.backgroundColor = 'salmon'; btn.style.color = 'white'; >);

We added an event listener to the button. The event listener invokes a function every time the button is clicked.

We used the style.backgroundColor property to change the button’s background color and the style.color property to change the font color of the button.

We used the document.getElementById() method to select the button by its id , however, you can also use the document.querySelector() method.

Copied!
const btn = document.querySelector('#btn'); btn.addEventListener('click', function onClick() btn.style.backgroundColor = 'salmon'; btn.style.color = 'white'; >);

The document.querySelector method returns the first element within the document that matches the specified selector.

The button has an id of btn , so its selector is #btn .

If you need to select a button by its class, prefix the selector with a dot, e.g. .btn .

Copied!
const btn = document.querySelector('.btn'); btn.addEventListener('click', function onClick() btn.style.backgroundColor = 'salmon'; btn.style.color = 'white'; >);

The code sample assumes that there is a button with a class name of btn on the page.

Copied!
button id="btn">Buttonbutton>

# Change a Button’s color every time it’s clicked

To change a button’s color every time it’s clicked:

  1. Add a click event listener to the button.
  2. Each time the button is clicked, set its style.backgroundColor property to a new value.
  3. Use an index variable to track the current and next colors.

Here is the HTML for this example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> button id="btn">Buttonbutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const btn = document.getElementById('btn'); let index = 0; const colors = ['salmon', 'green', 'blue', 'purple']; btn.addEventListener('click', function onClick() btn.style.backgroundColor = colors[index]; btn.style.color = 'white'; index = index >= colors.length - 1 ? 0 : index + 1; >);

If you load the page and click on the button, you’ll see that the button’s background color alternates between the colors in the array.

We used a counter variable that tracks the index of the color in the array.

Each time the button is clicked, we either increment the value in the index variable or set it back to 0 if the last color already was shown.

The ternary operator is very similar to an if/else statement.

If the expression to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.

You can imagine that the value before the colon is the if block and the value after the colon is the else block.

Copied!
const btn = document.getElementById('btn'); let index = 0; const colors = ['salmon', 'green', 'blue', 'purple']; btn.addEventListener('click', function onClick() btn.style.backgroundColor = colors[index]; btn.style.color = 'white'; index = index >= colors.length - 1 ? 0 : index + 1; >);

In the example, we check if the index variable stores a value that is equal to or greater than the last index in the colors array.

If we’ve reached the last index, we set the index variable back to 0 , otherwise, we increment the value stored in the variable by 1 .

This way, we are able to get a different background color every time we click the button.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to Change Button Color in Javascript

This article was co-authored by wikiHow staff writer, Darlene Antonelli, MA. Darlene Antonelli is a Technology Writer and Editor for wikiHow. Darlene has experience teaching college courses, writing technology-related articles, and working hands-on in the technology field. She earned an MA in Writing from Rowan University in 2012 and wrote her thesis on online communities and the personalities curated in such communities.

This article has been viewed 20,012 times.

This wikiHow article will teach you how to change the button color once it’s clicked using JavaScript. Changing the button color lets users know that they have already clicked the button on your page.

Image titled 12779919 1

Open your project in a Java-editing environment. This can be anything like Visual Studio or Oracle JDeveloper.

Image titled 12779919 2

script> document.getElementById("changeGreen").onclick = function() document.getElementById("output").style.color = 'green'; > document.getElementById("changeRed").onclick = function() document.getElementById("output").style.color = 'red'; > script> 
  • This code prompts the buttons to change the color of your text from green to red. You can replace these colors with others you prefer. [1] X Research source

Image titled 12779919 3

Enter the following code into your program if you want to change the button’s color when a text field is filled in:

DOCTYPE html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>Documenttitle> head> link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> script src="https://code.jquery.com/jquery-1.12.4.js">script> script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js">script> link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" /> body> label> UserName: label> input type="text" id="changeColorDemo" style="margin-left:10px;margin-top:10px" onkeyup="changeTheColorOfButtonDemo()"> br>br> button id="buttonDemo" style="background:skyblue;margin-left:10px;">Press Mebutton> body> script> function changeTheColorOfButtonDemo()  if (document.getElementById("changeColorDemo").value !== "")  document.getElementById("buttonDemo").style.background = "green"; > else  document.getElementById("buttonDemo").style.background = "skyblue"; > > script> html> 
  • Using an statement, the button is skyblue until the input field is filled, then it changes to a green button.
  • If you want to change the colors, you can either use color names like «Green» or «Skyblue,» Hexadecimal numbers (which you can find by searching Hexadecimal colors), or RGB colors (which you can also find by a simple internet search). To change the colors in the code, replace the «green» and «skyblue» colors in the code style.background .

Источник

Читайте также:  C cpp reference package
Оцените статью