1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScript ClickイベントとFunction(関数)

Posted at

#:white_check_mark:目標

JavaScriptでClickイベントを作る

#HTMLファイル

index.html
    <!DOCTYPE html>
    <html lang="ja">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>DOM</title>
        <style>
            .red {
                background: red;
                color: white;
                text-transform: uppercase;
                font-size: 2rem;
            }

            .blue {
                backgroun:white_check_mark:d: blue;
                color: white;
                text-transform: capitalize;
                letter-spacing: 10px;
            }

            .btn {
                background: #f15025;
                color: white;
                font-size: 1.2rem;
                border: none;
            }
        </style>
    </head>

    <body>

        <h2>events in javascript</h2>
        <button class="btn">click me</button>
        <!-- JavaScript -->
        <script src="main.js"></script>
    </body>

    </html>

#JavaScriptファイル

ボタンをクリックすると表示が切り替わります!

app.js
// Step1: select element
// Step2: addEventListener()
// Step3: what event, what todo

const btn = document.querySelector('.btn');
const heading = document.querySelector('h2');

function changeColors() {
    let hasClass = heading.classList.contains('red');
    console.log(hasClass);
    if (hasClass) {
        heading.classList.remove('red');
    } else {
        heading.classList.add('blue');
    }
}

btn.addEventListener('click', changeColors);
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?