엘리스 8일차 수요일 실시간 강의 javascript

치즈말랑이·2022년 4월 13일
0

엘리스

목록 보기
9/47
post-thumbnail

1. 이고잉님 강의

git commit -am "커밋메세지"; git push; git log

깃명령어 한번에 가능

브라우저 내장함수: build-ain function

애플리케이션 프로그래밍 인터페이스: api

day and night 복습

<!Doctype html>
<html>
 	<head>
 	</head>
	<body>
  	
  	<script>
  	
  	<input type="button" value="night" onclick="
	
	if (this.value==='night') {
    	document.querySelector('body').style.backgroundColor = 'black';
		document.querySelector('body').style.color = 'white';
		this.value = 'night';
    } else {
		document.querySelector('body').style.backgroundColor = 'white';
		document.querySelector('body').style.color = 'black';
		this.value = 'white';
    }
	
	">
  
  	</script>
  	
  	</body>
</html>

dotdotdot.html

...을 버튼으로 설정하여 누르면 글귀가 펼쳐지게 설정.

<html>
    <head>
    </head>
<body>

    
    javascript is <span 
        style="
        background-color: skyblue;
        padding: 0 5px;
        cursor:pointer;
        "
        onclick="
        document.querySelector('#hidden').style.display='inline';
        this.style.display='none';
    ">...</span> <span id="hidden" style="display:none;">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Consectetur id inventore in necessitatibus praesentium, minima corporis animi amet hic dolorem ratione nulla dolores. Corporis dolores omnis illum libero impedit necessitatibus.</span>

    <hr> <!-- 수평선 -->
    javascript is <span 
        style="
        background-color: skyblue;
        padding: 0 5px;
        cursor:pointer;
        "
        onclick="
        this.style.display='none';
        document.querySelector('#content').innerHTML = `Lorem ipsum dolor sit, amet consectetur adipisicing elit. Consectetur id inventore in necessitatibus praesentium, minima corporis animi amet hic dolorem ratione nulla dolores. Corporis dolores omnis illum libero impedit necessitatibus.`
    ">...</span> 
    <span id="content"></span>
    <!-- innerHTML 반드시 알아야함 -->
    <!-- 특정태그 안에 내용 넣을때, 가져올때 사용 -->
</body>
</html>

방법은 두가지이다.
1. 글귀를 span태그 안에 넣어 display:none 해뒀다가 ...을 누르면 display:inline으로 바꾸기
2. ...을 누르면 span태그 안에 글귀를 넣기

여기서 display="inline"을 처음 알았다.
display:"none"는 저번주에 css할때 배웠는데 생각을 못했다.

documennt.querySelector('body').innerHTML = '내용';
documennt.querySelector('.class').innerText = '내용';
documennt.querySelector('#id').textContent = '내용';

innerHTML, innerText, textContent 모두 querySelector로 선택한 요소에 내용을 추가하는건데, HTML은 html태그를 인식하고 나머지 두개는 태그가 사라지거나 인식되지 않는다.

flow-control-2.html

<html>
    <body>
        <h1>배열 - array</h1>
        <!-- 서로 연관된 데이터를 모아 그룹핑한 후에 이름 붙인 것이 배열이다. -->
        <ul>
            <li>html</li>
            <li>css</li>
            <li>js</li>
        </ul>
        <ul>
            <li>egoing</li>
            <li>leezche</li>
            <li>graphittie</li>
        </ul>
        <ul>
            <li>10</li>
            <li>css</li>
            <li>js</li>
        </ul>

        <script>
            let contents = ['html', 'css', 'js']
            let members = ['egoing', 'leezche', 'graphittie']
            let scores = [10, 20, 30]
            
            console.log(contents[0]);
            console.log(contents.length);
            console.log(contents);
            contents.push('react');
            console.log(contents);
        </script>

        <h1>Loop</h1>
        <script>
            // for (초기값, boolean => 반복조건, 카운팅 증감) {
            //     조건을 만족하는 동안 실행될 코드
            // }
            
            console.log(1);
            for(let i=0; i<3; i=i+1){
                console.log(2);
                console.log(3);
            }
            console.log(4);
        
        </script>
        <h2>Array + Loop</h2>
        <ul>
        <script>
            for(let i = 0; i<members.length; i++) {
                document.write('<li>' + members[i] + '</li>');
            }
        </script>
        </ul>
        <ul id='aa'>
        <script>
            let tag = "";
            for (i=0; i<contents.length; i++) {
                
                // tag += `<li> ${contents[i]} </li>`;
                // document.querySelector('#aa').innerHTML = tag;}
                document.querySelector('#aa').innerHTML += `<li> ${contents[i]} </li>`;}
        </script>
        </ul>
    </body>
</html>

for문 안에서 innerHTML이 돌아가면 루프가 돌때마다 innerHTML이 새로 업데이트되기때문에 += 를 사용한다.
혹은 어떤 변수에 담아서 거기에 += 한다음에 그 변수를 innerHTML에 넘겨줘도 된다.

function.html

<html>
    <body>
        <h1>Function</h1>
        <script>
            function 부가세계산(가격, 부가세율=0.1) {
                return (가격*부가세율);
            }
            console.log(부가세계산(1000, 0.1));
            alert(부가세계산(2000, 0.2));
            // file.save('result.txt', 부가세계산(2000));
            
        </script>
    </body>
</html>

함수 선언 방법

구글 teachablemachine (ml)

구글의 teachablemachine 사이트에 들어가면 머신러닝을 체험하고 프로젝트에 넣을수있게 해주는 서비스를 제공받을 수 있다.
https://teachablemachine.withgoogle.com/

day and night 함수 버전

<script>
            function night() {
                document.querySelector('body').style.backgroundColor = 'black';
                document.querySelector('body').style.color = 'white';
                let as = document.querySelectorAll('a');
                for(let i = 0; i<as.length; i++) {
                    as[i].style.color = 'white';}
            }
            function day() {
                document.querySelector('body').style.backgroundColor = 'white';
                document.querySelector('body').style.color = 'black';
                let as = document.querySelectorAll('a');
                for(let i = 0; i<as.length; i++) {
                    as[i].style.color = 'black';}
            }
            function dayNight(mode) {
                if(mode === 'night') {
                    night();
                } else {
                    day();
                }
            }
        </script>

        <input type="button" value="night" onclick="
        // 만약에 이 버튼의 value 값이 night라면 아래 코드가 실행되고,
        
        if (this.value === 'night') {
            // night();
            dayNight('night');
            this.value = 'day';
        } else {
        // 아니라면 아래 코드가 실행된다.
            // day();
            dayNight('day');
            this.value = 'night';
        }
        ">

html 코드를 깔끔하게 하기 위해 함수를 만들어서 사용한다.

2. 코치님 강의

addEventListener()

html요소.addEventListener(이벤트 종류, 이벤트 발생시 실행함수(콜백함수));
a.addEventListener('mouseenter', function () {
	함수내용
});
b.addEventListener('mouseleave', 함수이름);

addEventListener는 특정요소에 이벤트를 추가시켜주는 메서드이다.

document.querySelector('body').addEventListener 

이런식으로 써도 된다.
mouseenter는 마우스를 올렸을때, mouseleave는 마우스가 떠났을때 실행되는 이벤트조건이고 비슷하게 mouseover, mouseout이 있다.

그리고 파라미터 넘기는 부분에 event넘기는게 없는데, 안보이지만 event parameter가 넘어간다.

참고: https://hianna.tistory.com/492, https://recoveryman.tistory.com/51

onclick vs click

html 안에서는 onclick
vanila js 안에서는 click

classList.add()

classList는 css의 클래스를 자바스크립트에서 변경할수있게 하는 메서드이다.
a.css

.red {
	display:none;
}

b.js

this.classList.add('red');
this.classList.add('cursor');

cursor는 마우스모양을 손모양으로 바꿔준다.

참고: https://linuxhint.com/modify-css-classes-javascript/

scrollTo(options)

document.querySelector('body').addEventListener('click', function() {
  window.scrollTo({top:0, left:0, behavior:'smooth'});
  })

클릭하면 최상단으로 이동
scrollTo 에서 단순히 숫자만 (0,0) 쓰면 x,y좌표이고, top: left: behavior: 처럼 option으로 쓰면 애니메이션도 사용할 수 있다.

querySelector() vs. getElementById()

https://velog.io/@chloeee/getElementById-%EA%B7%B8%EB%A6%AC%EA%B3%A0-querySelector-%EC%B0%A8%EC%9D%B4%EC%A0%90

a.value

<input type="text" name="person" placeholder="오우.">

이 text필드에 적힌 값을 가져와서 변수로 저장하려면 다음과같이 하면 된다.

const a = document.querySelector('input');
a.value;

form 태그와 preventDefault()

form태그는 submit했을때 default로 리로드 된다.
이것을 막기 위해 preventDefault()를 사용한다.

form.addEventListener('submit', function(ev) {
    ev.preventDefault();
})

addEventListener는 자동으로 이벤트 parameter가 넘어가기때문에 function(ev)라고 쓰면 ev가 이 이벤트 parameter를 받는다.
참고: https://studyingych.tistory.com/27

createElement(), appendChild()

createElement(): html요소를 생성한다.

const textElement = document.createElement('p');
    textElement.textContent = '오우오우';

이러면 다음코드가 생성된다.

<p>'오우오우'</p>

appendChild(요소): 특정 html 요소 안에다가 괄호 안의 요소를 추가한다.

document.querySelector('body').appendChild(textElement);

body태그 안에 위에서만든

'오우오우'

요소가 생성된다.

참고: https://friedegg556.tistory.com/33

Event bubbling

https://codepen.io/bee-arcade/pen/NjRPzr/a068bd62a8981f08de0a468aafe5e44f?editors=0011
이 링크에 들어가서 inner box를 누르면 outer box까지 같이 눌린다. 이걸 event bubbling이라고 하는데, html이 다음과 같이 작성되어있기 때문이다.

<div id="outer">
      Click me!
      <div id="inner">
        No, click me!
      </div>
    </div>

즉, inner가 outer위에 겹쳐있기때문에 함께눌리는것이다.
이것을 막기 위해 inner 함수에 event.stopProgation()을 써준다.
https://codepen.io/bee-arcade/pen/vmXOZL/f26724e378ae61ebbb8e46c2745dd329?editors=0011

function onOuterClick() {
  outer.classList.add('selected');
  console.log('Outer clicked!');
}

function onInnerClick(event) {
  inner.classList.add('selected');
  console.log('Inner clicked!');
  event.stopPropagation();
}

const outer = document.querySelector('#outer');
const inner = document.querySelector('#inner');
outer.addEventListener('click', onOuterClick);
inner.addEventListener('click', onInnerClick);

반대로 큰범주에서 아래범주로 내려오는걸 caputre라고 한다.

profile
공부일기

0개의 댓글