상세 컨텐츠

본문 제목

[자바스크립트] 이벤트수신기

카테고리 없음

by esoesmio 2023. 5. 18. 21:48

본문

버튼에 이벤트 수신기 넣기

<!DOCTYPE html>
<html lang="en-US">
<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>

    <style>

    </style>
</head>
<body>

<button id="button1">
    버튼
</button>


<script>
    // // ♻️ 새로고침 후 실행
    // document.querySelector('#button1')
    //     .addEventListener('click', (e) => {
    //         console.log(e);
    //     });


    // ♻️ 새로고침 후 실행
    // document.querySelector('#button1')
    //     .addEventListener('click', function (e) {
    //         console.log(this);
    //         console.log(e);
    //         this.textContent = '클릭됨';
    //     });
    //
    //

    // ♻️ 새로고침 후 실행
    document.querySelector('#button1')
        .addEventListener('click', (e) => {
            console.log(this);
            console.log(e.target);
            e.target.textContent = '클릭됨';
        });


</script>
</body>
</html>

 

 

 

마우스 올려놓으면 올려놓지마라 그런거 이벤트수신기로

 

 

 

 

<!DOCTYPE html>
<html lang="en-US">
<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>

    <style>

    </style>
</head>
<body>

<button id="button2">
    버튼
   <div>
       secondbutton
   </div>


</button>


<script>
    const $button2 = document.querySelector('#button2');

    let timeout;
    let interval;
    let countdown;

    $button2.addEventListener('mouseenter', () => {
        if (timeout) clearTimeout(timeout);

        $button2
            .firstElementChild
            .textContent = '💣 치워라, 5초 준다';

        timeout = setTimeout(() => {
            $button2
                .firstElementChild
                .textContent = '🔥🔥🔥🔥🔥🔥🔥🔥🔥';
        }, 5000);
    });

    $button2.addEventListener('mouseleave', () => {
        if (timeout) clearTimeout(timeout);

        $button2
            .firstElementChild
            .textContent = '올리지 말라고 하면 올리지 마라';
    });

</script>
</body>
</html>

 

 

같은 이벤트에 대해 여러 핸들러 등록 가능

 

 

<!DOCTYPE html>
<html lang="en-US">
<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>

    <style>

    </style>
</head>
<body>

<button id="button2">
    버튼
   <div>
       secondbutton
   </div>


</button>


<script>

    const $button2 = document.querySelector('#button2');

    let timeout;
    let interval;
    let countdown;
    $button2.addEventListener('mouseenter', () => {
        if (interval) clearInterval(interval);

        countdown = 5;

        $button2
            .lastElementChild
            .textContent = countdown;

        interval = setInterval(() => {
            $button2
                .lastElementChild
                .textContent = --countdown;

            if (!countdown) clearInterval(interval);
        }, 1000);
    });

    $button2.addEventListener('mouseleave', () => {
        if (interval) clearInterval(interval);

        countdown = 0;

        $button2
            .lastElementChild
            .textContent = countdown;
    });
</script>
</body>
</html>

 

 

 

포커스되면 어! 왜 뭐입력하시게요

 

아니면 그낭가시네...

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <style>

    </style>
</head>
<body>
<input type="text" id = "input1">
</body>

<script>
    const $input1 = document.querySelector('#input1');
    $input1.addEventListener('focus', () => {
        $input1.setAttribute('placeHolder', '어! 왜, 뭐 입력하시게요?');
    });
    $input1.addEventListener('blur', () => {
        $input1.setAttribute('placeHolder', '그냥 가시네...');
    });


</script>
</html>

 

 

 

키보드가 눌릴때

 

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <style>

    </style>
</head>
<body>

<ul>
</ul>
<input type="text" id = "input2">

</body>

<script>


    const $ul = document.querySelector('ul');
    const $input2 = document.querySelector('#input2');


    $input2.addEventListener('keyup', (e) => {
        if (e.key !== 'Enter') return;

        $newLi = document.createElement('li');
        $newLi.textContent = e.target.value;
        // $newLi.textContent = '시부럴';
        $ul.appendChild($newLi);

        e.target.value = '';
    });
</script>
</html>

 

 

정렬하는거 달리기순서

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <style>
        body {
            padding: 16px 32px;
            font-size: 1.2em;
        }

        table {
            border-collapse: collapse;
        }

        th, td {
            text-align: center;
            padding: 8px 16px;
            border: 1px solid #ddd;
        }

        th {
            background-color: #eee;
            border-bottom: 2px solid #ddd;
        }

        select, input {
            margin-bottom: 18px;
            font-size: 1em;
            padding: 4px 8px;
        }

        input {
            margin-left: 16px;
        }
    </style>
</head>
<body>

<h1>달리기 경주 기록</h1>

<select id="school">
    <option value="">전체 학교</option>
    <option value="근성">근성대</option>
    <option value="복근">복근대</option>
    <option value="박력">박력대</option>
</select>

<input type="number" id="grade" value="1" min="1" max="4">
<label for="sort">학년 이상</label>

<input type="checkbox" id="sort">
<label for="sort">기록순 정렬</label>

<table>
    <thead>
    <tr>
        <th>번호</th>
        <th>학교</th>
        <th>학년</th>
        <th>이름</th>
        <th>기록</th>
    </tr>
    </thead>
    <tbody id="raceTbody">
    <tr>
        <td>2</td>
        <td>복근대학교</td>
        <td>4</td>
        <td>전우치</td>
        <td>1198.4922</td>
    </tr>
    <tr>
        <td>4</td>
        <td>박력대학교</td>
        <td>4</td>
        <td>김두한</td>
        <td>1218.7154</td>
    </tr>
    <tr>
        <td>5</td>
        <td>복근대학교</td>
        <td>2</td>
        <td>김춘삼</td>
        <td>1374.5151</td>
    </tr>
    <tr>
        <td>1</td>
        <td>근성대학교</td>
        <td>3</td>
        <td>홍길동</td>
        <td>1454.3881</td>
    </tr>
    </tbody>
</table>


</body>
</body>

<script>
    let raceData;
    getRaceData();

    async function getRaceData () {
        const SERVER_URL = 'https://showcases.yalco.kr/javascript/mockserver/';

        // 경주 기록 받기
        const raceResult = await fetch(SERVER_URL + 'race-result')
            .then(result => result.json());
        console.log('1.', raceResult);
console.log(typeof raceResult);
        const runners = [];
        const runnerIdxs = raceResult
            .map(itm => itm['runner_idx']);
console.log(typeof runnerIdxs);
        // 기록상 주자 번호에 따라 주자들의 정보 받기
        for (const runnerIdx of runnerIdxs) {
            const runner = await fetch(`${SERVER_URL}runners/${runnerIdx}`)
                .then(result => result.json())
            runners.push(runner);
        }
        console.log('2.', runners);

        // 주자들의 학교 번호 중 중복을 거른 뒤 이에 따라 학교 정보 받기
        const schools = [];
        const schoolIdxs = [
            ...new Set(
                runners.map(itm => itm['school_idx'])
            )
        ];
        for (const schoolIdx of schoolIdxs) {
            const school = await fetch(`${SERVER_URL}schools/${schoolIdx}`)
                .then(result => result.json())
            schools.push(school);
        }
        console.log('3.', schools);

        // 세 배열의 객체들을 조인
        raceData = raceResult
            .map(result => {
                const runner = {
                    ...runners
                        .find(({idx}) => idx === result.runner_idx)
                }

                runner.school = schools
                    .find(({idx}) => idx === runner.school_idx)
                    .name

                delete runner.school_idx;
                delete runner.idx;

                return {
                    ...result,
                    ...runner
                }
            });
        console.log('4.', raceData);

        fillRaceTable();
    }

    function fillRaceTable () {

        // 배열 복사
        let data = [...raceData];

        const _school = document.querySelector('#school').value;
        const _grade = document.querySelector('#grade').value;
        const _sort = document.querySelector('#sort').checked;

        // 인풋 요소의 값들에 따라 필터링 또는 정렬
        if (_school) data = data.filter(({school}) => school.startsWith(_school));
        if (_grade) data = data.filter(({grade}) => grade >= _grade);
        if (_sort) data.sort((a, b) => a.record - b.record);

        // 먼저 tbody 부분을 비움
        const $tbody = document.querySelector('#raceTbody');
        while ($tbody.firstChild) {
            $tbody.removeChild($tbody.firstChild);
        }

        // tbody 채워넣기
        data.forEach(datum => {
            const $newTr = document.createElement('tr');

            ['runner_idx', 'school', 'grade', 'name', 'record']
                .forEach(itm => {
                    const $newTd = document.createElement('td');
                    $newTd.textContent = datum[itm];
                    $newTr.appendChild($newTd);
                });
            $tbody.appendChild($newTr);
        });
    }
    document.querySelector('#school')
        .addEventListener('change', (e) => {
            console.log(e.target.value);
            fillRaceTable();
        });

    document.querySelector('#grade')
        .addEventListener('change', () => {
            fillRaceTable();
        });

    document.querySelector('#sort')
        .addEventListener('change', () => {
            fillRaceTable();
        });
</script>
</html>

 

 

댓글 영역