Как при нажатии на кнопку изменить цвет текста js

I want to change the color of a title when a button is clicked. This is my code, but it's not working and I can't figure out why not... var about; function init() { about = document.

I want to change the color of a title when a button is clicked.
This is my code, but it’s not working and I can’t figure out why not…

var about;   
function init() { 
    about = document.getElementById("about").innerHTML;
    about.style.color = 'blue';
}
<div id="about">About Snakelane</div>
 
<input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn">

Tomerikoo's user avatar

Tomerikoo

17.6k16 gold badges41 silver badges59 bronze badges

asked Jul 29, 2013 at 13:38

You set the style per element and not by its content:

function init() { 
  document.getElementById("about").style.color = 'blue';
}

With innerHTML you get/set the content of an element. So if you would want to modify your title, innerHTML would be the way to go.

In your case, however, you just want to modify a property of the element (change the color of the text inside it), so you address the style property of the element itself.

answered Jul 29, 2013 at 13:40

Sirko's user avatar

SirkoSirko

71.4k19 gold badges146 silver badges180 bronze badges

use ONLY

function init() { 
    about = document.getElementById("about");
    about.style.color = 'blue';
}

.innerHTML() sets or gets the HTML syntax describing the element’s descendants., All you need is an object here.

Demo

animuson's user avatar

animuson

53.2k28 gold badges142 silver badges147 bronze badges

answered Jul 29, 2013 at 13:40

Dhaval Marthak's user avatar

Dhaval MarthakDhaval Marthak

17.2k6 gold badges43 silver badges68 bronze badges

Try below code:

$(document).ready(function(){
$('#about').css({'background-color':'black'});    
});

http://jsfiddle.net/jPCFC/

answered Jul 29, 2013 at 13:45

Nitin Chaurasia's user avatar

1

innerHTML is a string representing the contents of the element.

You want to modify the element itself. Drop the .innerHTML part.

answered Jul 29, 2013 at 13:40

Quentin's user avatar

QuentinQuentin

893k122 gold badges1194 silver badges1316 bronze badges

I am getting back into learning Javascript and am running into trouble with changing text color when clicking a button.

A lot of the other questions have referenced changing the color of the button itself, and the code I have does not seem to have an error.

<body>
<h1>My First Web Page</h1>
<p>Exciting stuff! This is my first web page.</p>
<button id= “color”>Change color!</button>
<script>
document.getElementById('color').onclick = changeColor; var currentColor = “red”;
function changeColor() { 
        if(currentColor == “red”){ 
    document.body.style.color = “green”;
    currentColor = “green”;
        } else {
        document.body.style.color = “red”;
        currentColor = “red”;
        } 
            return currentColor; 
    }
</script>
</body>

However, the line

document.getElementById('color').onclick = changeColor; var currentColor = “red”;

generates an error saying that it is an illegal token. Initially, I thought the issue had to do with not putting the code in a form. The instructional video’s demonstration seemed to work fine, but I keep getting this error. Can anyone provide an idea what is going wrong?

Mihai Alexandru-Ionut's user avatar

asked Jan 29, 2017 at 19:05

Louis 's user avatar

Your code works perfectly but you use incorrect syntax. Change to "
quotation marks.

Also, you do not need to use return statement inside the function, which represents onclick event handler.

<body>
<h1>My First Web Page</h1>
<p>Exciting stuff! This is my first web page.</p>
<button id= "color">Change color!</button>
<script>
document.getElementById('color').onclick = changeColor; 
var currentColor = "red";
function changeColor() { 
        if(currentColor == "red"){ 
           document.body.style.color = "green";
           currentColor = "green";
        } else {
           document.body.style.color = "red";
           currentColor = "red";
        } 
    }
</script>
</body>

answered Jan 29, 2017 at 19:10

Mihai Alexandru-Ionut's user avatar

1

I am getting back into learning Javascript and am running into trouble with changing text color when clicking a button.

A lot of the other questions have referenced changing the color of the button itself, and the code I have does not seem to have an error.

<body>
<h1>My First Web Page</h1>
<p>Exciting stuff! This is my first web page.</p>
<button id= “color”>Change color!</button>
<script>
document.getElementById('color').onclick = changeColor; var currentColor = “red”;
function changeColor() { 
        if(currentColor == “red”){ 
    document.body.style.color = “green”;
    currentColor = “green”;
        } else {
        document.body.style.color = “red”;
        currentColor = “red”;
        } 
            return currentColor; 
    }
</script>
</body>

However, the line

document.getElementById('color').onclick = changeColor; var currentColor = “red”;

generates an error saying that it is an illegal token. Initially, I thought the issue had to do with not putting the code in a form. The instructional video’s demonstration seemed to work fine, but I keep getting this error. Can anyone provide an idea what is going wrong?

Mihai Alexandru-Ionut's user avatar

asked Jan 29, 2017 at 19:05

Louis 's user avatar

Your code works perfectly but you use incorrect syntax. Change to "
quotation marks.

Also, you do not need to use return statement inside the function, which represents onclick event handler.

<body>
<h1>My First Web Page</h1>
<p>Exciting stuff! This is my first web page.</p>
<button id= "color">Change color!</button>
<script>
document.getElementById('color').onclick = changeColor; 
var currentColor = "red";
function changeColor() { 
        if(currentColor == "red"){ 
           document.body.style.color = "green";
           currentColor = "green";
        } else {
           document.body.style.color = "red";
           currentColor = "red";
        } 
    }
</script>
</body>

answered Jan 29, 2017 at 19:10

Mihai Alexandru-Ionut's user avatar

1

Смена цвета через js — мы можем поменять цвет, либо при наведении, либо при клике(onclick). разберем несколько способов менять цвет с помощью javascript.

  • Сменить цвет(background) при наведении мышки javascript

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

    Html + Css

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

    добавим style

    + width

    + height

    + background color

    + id

    и получим:

    <div style=»width:500px;height:100px;background:yellow» id=»example»></div>

    javascript

    Нам понадобится: script

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

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

    <script>
    example.onmouseover = function() {
    example.style.background= «red»;
    };

    example.onmouseleave = function() {
    example.style.background= «yellow»;
    };
    </script>

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

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

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

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

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

    добавим style

    + width

    + height

    + background color

    добавим onclick

    и this,

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

    <div style=»width:500px;height:100px;background:yellow» onclick=»this.style.background=’red'»></div>

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

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

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

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

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

    Нам опять нужен элемент… + id

    <div id=change_background>здесь background</div>

    Обратимся к элементу через id

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

    <style>
    #change_background{width:500px;height:100px;background:yellow}
    </style>

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

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

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

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

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

    , то меняем его на #efefef

    if_id .style . background = «#efefef»;

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

    if_id .style . background = «red»;

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

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

    <script>

    document.addEventListener("click", function(e)

    {

      if_id = e . target. id;

      if(if_id == "change_background")

      {

        if_id = document.getElementById(if_id);

        if(if_id .style . background == "red")

        {

            if_id .style . background = "#efefef";

        }

        else

        {

            if_id .style . background = "red";

        }

      }

    });

    </script>

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

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

    здесь background

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

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

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

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

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

    Пример кнопок:

    <button class=»click_me» id=»id_1″>Измени цвет кнопки</button>
    <button class=»click_me» id=»id_2″>Измени цвет кнопки</button>
    <button class=»click_me» id=»id_3″>Измени цвет кнопки</button>

    javascript

    Возьмем один из способов onclick

    document.addEventListener(«click», function(e)

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

    if_id = e . target. id;
    the_class = e . target.className;

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

    if(the_class == «click_me»)

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

    if_id = document.getElementById(if_id);

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

    if(if_id .style . background == «red»)
    {
    if_id .style . background = «#efefef»;
    }

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

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

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


    Html:

    <button class="click_me" id="id_1">Измени цвет кнопки</button>

    <button class="click_me" id="id_2">Измени цвет кнопки</button>

    <button class="click_me" id="id_3">Измени цвет кнопки</button>

    javascript

    <script>

    document.addEventListener("click", function(e)

    {

      if_id = e . target. id;

      the_class = e . target.className;

      if(the_class == "click_me")

      {

        if_id = document.getElementById(if_id);

        if(if_id .style . background == "red")

        {

          if_id .style . background = "#efefef";

        }

        else

        {

          var links = document.querySelectorAll(".click_me");

          links.forEach(link => {

            link.setAttribute("style", "background:#efefef");

          })

          if_id .style . background = "red";

        }

      }

    });

    </script>

    Результат изменения цвета при нажатии на элемент

    How to change the text color in JavaScript:

    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.

    Property to change:

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

    Example program:

    Create one index.html file with the below content:

    <!DOCTYPE html>
    <html>
    
    <head>
        <title>Change Color in JS</title>
    </head>
    
    <body>
        <button id="toBlue">Blue</button>
        <button id="toGreen">Green</button>
        <button id="toRed">Red</button>
        <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>

    Output:

    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.

    Explanation:

    Here,

    • 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.

    You might also like:

    • Example of JavaScript reduce with an array of objects
    • JavaScript setDate function explanation with example
    • JavaScript program to read the current date time
    • JavaScript program to find the sum of all even numbers below a given number
    • JavaScript program to find the lcm of two numbers
    • Different index related methods in JavaScript array

    Если ты принял компульсивное решение изучать JavaScript и теперь сидишь в шоке, то мы подготовили небольшой пример, который покажет тебе базовую концепцию DOM и работу с объектами.

    Чуть-чуть теории

    Document Object Model, сокращённо DOM – объектная модель документа, которая представляет все содержимое страницы в виде объектов, которые можно менять.

    Объект document – основная «входная точка». С его помощью мы можем что-то создавать или менять на странице. И именно DOM позволяет нам получать доступ к элементам страницы с помощью JavaScript.

    Получив с сервера документ, парсер браузера каждый тег превращает в узел и строит их иерархию. В результате получается дерево узлов (node), или просто DOM-дерево, в котором вложенные элементы представлены в виде дочерних узлов с полным набор атрибутов. Подробнее про DOM — тут.

    Каждый элемент страницы является объектом Например, можем поменять цвет фона на черный

    #меняем фон на черный
    document.body.style.background = "black"

    Поиск элемента по ID

    Окей, мы можем менять какие-то параметры конкретного элемента. Но что, если код растянется на сотни или тысячи строк? Как нам найти конкретный элемент над которым мы будем работать?

    Собственно, «искать» не обязательно- мы можем вызвать какой-либо уникальный элемент на странице, у которого есть атрибут id (обозначается символом #) с помощью document.getElementById(id). Например:

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1 id="demo">The Document Object</h1>
    <h2>The getElementById() Method</h2>
    
    <script>
    const myElement = document.getElementById("demo");
    myElement.style.color = "red";
    </script>
    
    </body>
    </html>
    

    Значение id должно быть уникальным. В документе может быть только один элемент с данным id. Результат:

    Поиск элемента по селектору

    Выцеплять элементы по ID не очень удобно с практической точки зрения. Наиболее универсальный метод поиска – это querySelectorAll(css), он возвращает все элементы, удовлетворяющие данному CSS-селектору.

    Также существует «обычная» конструкция querySelector. Единственная разница между querySelectorAll и querySelector в том, что первый возвращает массив элементов, а второй только первый элемент найденный на странице.

    Этот метод действительно мощный, потому что можно использовать любой CSS-селектор. А их достаточно много. Например:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Использование JavaScript метода document.querySelectorAll() (перебор элементов в цикле)</title>
        </head>
        <body>
            <button onclick = "myFunc()">Нажми меня</button> <!-- добавляем атрибут событий onclick -->
            <div class = "block">Первый блок</div>
            <div class = "block">Второй блок</div>
            <div class = "block">Третий блок</div>
            <script>
        function myFunc() {
          let blocks = document.querySelectorAll( ".block" ); // находим все элементы с классом block
          for( let i = 0; i < blocks.length; i++){ // проходим циклом по всем элементам объекта
            blocks[i].style.color = "red"; // устанавливаем красный цвет текста каждому элементу
          }		
        }
            </script>
        </body>
    </html>

    События

    Когда нам нужно выполнить какой-то код при клике или при наведении на элемент — используется событие. Событие – это сигнал от браузера о том, что что-то произошло. На каждый DOM-элемент можно повесить такой эвент. Какие события могут быть:

    • click – происходит, когда кликнули на элемент левой кнопкой мыши (на устройствах с сенсорными экранами оно происходит при касании).
    • contextmenu – происходит, когда кликнули на элемент правой кнопкой мыши.
    • mouseover / mouseout – когда мышь наводится на / покидает элемент.
    • mousedown / mouseup – когда нажали / отжали кнопку мыши на элементе.
    • mousemove – при движении мыши.

    JavaScript позволяет при обнаружении нужного события выполнить необходимый код. Для этого у HTML элементов есть специальные атрибуты обработчики событий (браузеру нужно понимать, что делать при наступлении какого-либо события)

    Такой обработчик мы можем положить прямо в атрибут элемента:

    <button type="button" style="display: block;" onclick="changeColor();">Change color </button>

    В нашем примере мы напишем скрипт, который позволит по клику (тапу) на кнопку сделать однократное изменение цвета всех квадратов с синего на красный.

    Практика

    Для начала накидаем структуру. На странице у нас будет кнопка с атрибутом onlclick (туда мы передаем JS-функцию, которую напишем далее) и несколько блоков div с классом square. В кнопку прописываем атрибут обработчик, функция которого которая назначена у нас на кнопку Change Color

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1>Нажми на кнопку, чтобы изменить цвет элемента</h1>
    <button type="button" style="display: block;" onclick="changeColor();">Change color </button>
    
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    
    </body>
    </html>

    Опишем через css параметры класса square. По теории мы помним, что нам для функции будет нужен именно селектор класса, чтобы применить стиль к нескольким элементам на странице

    .square {
      width: 100px;
      height: 100px;
      background-color: blue;
      margin: 10px;
      display: inline-block;
    }

    Теперь непосредственно сам код JS. Пишем функцию, которую прописали в обработчике. В нашем случае document.getElementById(id) не подходит — у нас несколько элементов на странице, поэтому используем document.querySelectorAll. Внутри указываем наш класс. Метод forEach() выполняет указанную функцию один раз для каждого элемента в массиве.

       function changeColor() {
    document.querySelectorAll(".square").forEach(v => v.style.backgroundColor = "red");
    }

    Посмотреть пример

    Понравилась статья? Поделить с друзьями:
  • Как при нажатии на кнопку изменить css
  • Как при звонке изменить голос на мужской телефонном разговоре
  • Как при дублировании экранов изменить разрешение у другого
  • Как при hover изменить другой элемент
  • Как премьер про изменить размер холста