2016년 7월 29일 금요일

05day Javascript + HTML5

HTML5

  • Tag추가
    • sementic Tag
    • form 
  • Javascript Library
    • 미디어
      • audio   ←옛날에는 embed +active-x / flash
      • video
      • canvas : 자바스크립트로 그림 그려줌
      • svg : svg라는 xml 태그를 통해서 그림을 그려줌


1. HTML5 수업 세팅

HTML5 Video
브라우저마다 지원하는 동영상 종류가 다름
**스트리밍이나 인터넷 방송은 다른 방식을 사용


2
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- HTML5 video태그 -->
<video width='320' height='240' controls="controls">
    <!-- 브라우저 비디오지원 선택사항 -->
    <source src="./video/movie.mp4" type='video/mp4'>
    <source src="./video/movie.ogg" type='video/ogg'>
    Your browser does not support the video tag.
</video>

</body>
</html>


3
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.button {
    -moz-box-shadow:inset 0px 1px 0px 0px #fce2c1;
    -webkit-box-shadow:inset 0px 1px 0px 0px #fce2c1;
    box-shadow:inset 0px 1px 0px 0px #fce2c1;
    background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffc477), color-stop(1, #fb9e25) );
    background:-moz-linear-gradient( center top, #ffc477 5%, #fb9e25 100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc477', endColorstr='#fb9e25');
    background-color:#ffc477;
    -webkit-border-top-left-radius:20px;
    -moz-border-radius-topleft:20px;
    border-top-left-radius:20px;
    -webkit-border-top-right-radius:20px;
    -moz-border-radius-topright:20px;
    border-top-right-radius:20px;
    -webkit-border-bottom-right-radius:20px;
    -moz-border-radius-bottomright:20px;
    border-bottom-right-radius:20px;
    -webkit-border-bottom-left-radius:20px;
    -moz-border-radius-bottomleft:20px;
    border-bottom-left-radius:20px;
    text-indent:0;
    border:1px solid #eeb44f;
    display:inline-block;
    color:#ffffff;
    font-family:Arial;
    font-size:15px;
    font-weight:bold;
    font-style:normal;
    height:50px;
    line-height:50px;
    width:100px;
    text-decoration:none;
    text-align:center;
    text-shadow:1px 1px 0px #cc9f52;
}
.button:hover {
    background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #fb9e25), color-stop(1, #ffc477) );
    background:-moz-linear-gradient( center top, #fb9e25 5%, #ffc477 100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fb9e25', endColorstr='#ffc477');
    background-color:#fb9e25;
}.button:active {
    position:relative;
    top:1px;
}</style>
/* This button was generated using CSSButtonGenerator.com */
<script type="text/javascript">
    window.onload= function(){
        //자바스크립트로 비디오 제어
        var myVideo = document.getElementById('video');
        
        document.getElementById('btn1').onclick = function(){
            if(myVideo.paused){  //플레이와 일시정지 버튼
                myVideo.play();
            }else{
                myVideo.pause();
            }
        }
    }
</script>
</head>
<body>

<!-- HTML5 video태그 -->
<button id='btn1' class='button'>play/pause</button><br><br>

<video id='video' width='320' height='240'>
    <source src="./video/mov_bbb.mp4" type='video/mp4'>
    <source src="./video/mov_bbb.ogg" type='video/ogg'>
    Your browser does not support the video tag.
</video>

</body>
</html>


4
브라우저마다 지원하는 오디오 방식이 다름


5. SVG-Scalable Vector Graphics
그림크기가 확대되어도 이미지가 깨지지 않음
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- svg 원그리기-->
<svg width='100' height='100'>
    <circle cx='50' cy='50' r='40' fill='yellow' />
</svg>
<!-- 사각형 라운드 그리기 -->
<svg width="400" height="180">
  <rect x="50" y="20" rx="20" ry="20" width="150" height="150" style="fill:red;stroke:black;stroke-width:5;opacity:0.5">
  Sorry, your browser does not support inline SVG.
</svg>
</body>
</html>


6
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<!-- svg 다각형-->
<svg height='210' width='500'>
    <polygon points="100,10 40,198 190,78 10,78 160,198" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:nonzero;"/>
</svg>

</body>
</html>


7
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<!-- svg path 수학도형표시-->
<svg height="400" width="450">
<path id="lineAB" d="M 100 350 l 150 -300" stroke="red" stroke-width="3" fill="none" />
  <path id="lineBC" d="M 250 50 l 150 300" stroke="red" stroke-width="3" fill="none" />
  <path d="M 175 200 l 150 0" stroke="green" stroke-width="3" fill="none" />
  <path d="M 100 350 q 150 -300 300 0" stroke="blue" stroke-width="5" fill="none" />
  <!-- Mark relevant points -->
  <g stroke="black" stroke-width="3" fill="black">
    <circle id="pointA" cx="100" cy="350" r="3" />
    <circle id="pointB" cx="250" cy="50" r="3" />
    <circle id="pointC" cx="400" cy="350" r="3" />
  </g>
  <!-- Label the points -->
  <g font-size="30" font-family="sans-serif" fill="black" stroke="none" text-anchor="middle">
    <text x="100" y="350" dx="-30">A</text>
    <text x="250" y="50" dy="-10">B</text>
    <text x="400" y="350" dx="30">C</text>
  </g>
  Sorry, your browser does not support inline SVG.
</svg>

</body>
</html>


svg로 차트를 그림 --http://www.highcharts.com/ 무료 https://d3js.org/
8. canvas
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #canvas { border: 1px solid black; }
</style>
<script type="text/javascript">
    window.onload = function(){
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        ctx.fillStyle = '#ff0000';
        ctx.fillRect(10,10,150,75);
    }
</script>
</head>
<body>
<!-- canvas 그림그리기 javascript 이용-->
<canvas id='canvas' width='500' height='500'></canvas>

</body>
</html>


9
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #canvas { border:1px solid #d3d3d3; }
</style>
<script type="text/javascript">
    window.onload = function(){
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        //canvas에 글씨 넣기
        ctx.font = '60px Comic Sans Ms';
        ctx.fillStyle = 'red';
        ctx.textAlign = 'center';
        ctx.fillText('Hello World', canvas.width/2, canvas.height/2);
    }
</script>
</head>
<body>
<!-- canvas 그림그리기 javascript 이용-->
<canvas id="canvas" width="500" height="200"></canvas>

</body>
</html>


10
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #canvas { border:1px solid black; }
</style>
<script type="text/javascript">
    window.onload = function(){
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        //canvas에 이미지 넣기
        var image = new Image();
        image.src = './images/Tulips.jpg';
        image.onload = function(){
            ctx.drawImage(image,0,0);
        }
    }
</script>
</head>
<body>
<!-- canvas 그림그리기 javascript 이용-->
<canvas id="canvas" width="500" height="200"></canvas>

</body>
</html>


11
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
div{
    font-size: 30px;
    border: 1px solid blue;
    padding: 10px;
}
</style>
<script type="text/javascript">
    var context;
    var dig;
    
    var dialImg = new Image();
    var hourImg = new Image();
    var minImg = new Image();
    var secImg = new Image();
    
    dialImg.src = "images/dial.png";
    hourImg.src = "images/pin_3.png";
    minImg.src = "images/pin_2.png";
    secImg.src = "images/pin_1.png";
    
    var rHour = 0.0, rMin=0.0, rSec=0.0;
    var centerX, centerY;
    
    window.onload=function(){
        var canvas=document.getElementById('myCanvas');
        dig = document.getElementById('digital');
        context = canvas.getContext('2d');
        
        centerX=300/2;
        centerY=300/2;
        
        setInterval(showTime, 50);
    }
    
    function drawCanvas(){
        context.drawImage(dialImg, centerX-150, centerY-150, 300, 300);
        context.save();
        
        context.translate(centerX, centerY);
        context.rotate(rSec);
        context.drawImage(secImg, -10, -130, 20, 130);
        context.restore();
        context.save();
        
        context.translate(centerX, centerY);
        context.rotate(rMin);
        context.drawImage(minImg, -10, -130, 20, 130);
        context.restore();
        context.save();
        
        context.translate(centerX, centereY);
        context.rotate(rHour);
        context.drawImage(hourImg, -10, -130, 20, 130);
        context.restore();
    }
    
    function showTime() {
        var d = new Date();
        var hour = d.getHours();
        var min = d.getMinutes();
        var sec = d.getSeconds();
        
        rSec = (6 * sec) * (Math.PI / 180);
        rMin = (6 * min) * (Math.PI / 180) + (6 * rSec / 360);
        rHour = (30 * hour) * (Math.PI / 180) + (30 * rMin / 360);
        drawCanvas();
        
        log(hour + "시 " + min + "분 " + sec + "초")
    }
    
    function log(msg) {
        dig.innerHTML = msg;
    }
</script>
</head>
<body>
    <div align="center">
        <canvas id="myCanvas" width="300" height="300"></canvas>
        <p font‐size="50px">현재시각</p>
        <div id="digital" style="width: 300px; border: 2px solid red; font‐size: 30px"></div>
    </div>
</body>
</html>


12
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //HTML5 Geolocation  //모바일 활용을 위해서 만들어짐, 컴퓨터는 네트워크를 통해서 geo를 받아옴
    var result;
    window.onload= function(){
        result = document.getElementById('result');
        if(navigator.geolocation){
            //result.innerHTML = 'Geolocation 지원';
            //컴퓨터의 geo정보를 가져오는데 시간이 걸리기때문에 callback - 함수 호출기법 사용
            navigator.geolocation.getCurrentPosition(showPosition);
            /* navigator.geolocation.getCurrentPosition(function(){
                alert('showPosition 호출')
            }); */
        }else{
            result.innerHTML = 'Geolocation 미지원';
        }
    };
    var showPosition = function(position){
        alert('showPosition 호출');
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        
        var msg = '위도 : '+latitude + '/ 경도 : ' + longitude;
        result.innerHTML=msg;
    };
</script>
</head>
<body>

<div id='result'></div>

</body>
</html>


13
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //HTML5 Geolocation  //모바일 활용을 위해서 만들어짐, 컴퓨터는 네트워크를 통해서 geo를 받아옴
    var result;
    window.onload= function(){
        result = document.getElementById('result');
        if(navigator.geolocation){
            //getCurrentPosition(정상출력, 비정상일때 출력)
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        }else{
            result.innerHTML = 'Geolocation 미지원';
        }
    };
    var showPosition = function(position){
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        
        var msg = '위도 : '+latitude + '/ 경도 : ' + longitude;
        result.innerHTML=msg;
    };
    //에러 처리
    var showError = function(error) {
        switch(error.code) {
            case error.PERMISSION_DENIED:
                result.innerHTML = "User denied the request for Geolocation."
                break;
            case error.POSITION_UNAVAILABLE:
                result.innerHTML = "Location information is unavailable."
                break;
            case error.TIMEOUT:
                result.innerHTML = "The request to get user location timed out."
                break;
            case error.UNKNOWN_ERROR:
                result.innerHTML = "An unknown error occurred."
                break;
        }
    }
</script>
</head>
<body>

<div id='result'></div>

</body>
</html>


14. 자바스크립트로 구글지도 api 불러오기
구글에서 api key를 받아야함
https://developers.google.com/maps/documentation/javascript/?hl=ko


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    * {margin: 0; padding: 0;}
    html, body{ height:100%;}
    #map {height: 100%;}
</style>
<!-- 구글 지도 자바스크립트 라이브러리 가져옴 -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=구글제공개인KEY&sensor=false"></script>
<script type="text/javascript">
    window.onload = function(){
        var element = document.getElementById('map');
        //맵 표시
        var map = new google.maps.Map(element,{
            zoom: 14,
            center: new google.maps.LatLng(37.49865608828099,127.02834066144196),
            mapTypeId: google.maps.MapTypeId.ROADMAP
            //mapTypeId: google.maps.MapTypeId.SATELLITE  //위성
            //mapTypeId: google.maps.MapTypeId.HYBRID   //로드맵 + 위성
        });
        
        //위치 표시
        new google.maps.Marker({
            position: new google.maps.LatLng(37.49865608828099,127.02834066144196),
            map: map,
            title: 'Hello Position'
        })
    }
</script>
</head>
<body>

<div id="map"></div>

</body>
</html>


15
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    * {margin: 0; padding: 0;}
    html, body{ height:100%;}
    #map {height: 100%;}
</style>
<!-- 구글 지도 자바스크립트 라이브러리 가져옴 -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=구글제공API키&sensor=false"></script>
<script type="text/javascript">
    window.onload = function(){
        var element = document.getElementById('map');
        
        //현재위치 확인
        navigator.geolocation.getCurrentPosition(function(position){
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            
            //맵 표시
            var map = new google.maps.Map(element,{
            zoom: 14,
            center: new google.maps.LatLng(latitude,longitude),
            mapTypeId: google.maps.MapTypeId.ROADMAP
            });
        

            //위치 표시
            new google.maps.Marker({
            position: new google.maps.LatLng(latitude,longitude),
            map: map
            });    
        }, function(error){
            alert('error');
        });
    };
    
</script>
</head>
<body>

<div id="map"></div>

</body>
</html>


16
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #target { width: 350px; height: 70px; padding: 10px; border: 1px solid black; }
</style>
<script type="text/javascript">
    var allowDrop=function(e){
        //dragover 대한 기본 이벤트 제거
        e.preventDefault();
    };
    
    var drag = function(e){
        //img - html 태그 - id값
        e.dataTransfer.setData('text', e.target.id);
    };
    var drop = function(e){
        e.preventDefault();
        var data = e.dataTransfer.getData('text');
        e.target.appendChild(document.getElementById(data));
    };
    
</script>
</head>
<body>
<!-- 드롭했을때, 드롭완료시 이벤트 검 -->
<div id="target" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

<br />
<!-- 이미지를 드레그 가능하게 만듦, 드레그를 시작할 떄 이벤트검 -->
<img src="./images/img_logo.gif" width="336" height="69" id="drag1" draggable="true" ondragstart="drag(event)"/>
</body>
</html>


17
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #div1, #div2
    {float:left; width:100px; height:35px; margin:10px;padding:10px;border:1px solid #aaaaaa;}
</style>
<script type="text/javascript">
    function allowDrop(ev) {
        ev.preventDefault();
    }
    
    function drag(ev) {
        ev.dataTransfer.setData("text", ev.target.id);
    }
    
    function drop(ev) {
        ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
</script>
</head>
<body>
    <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
      <img src="./images/img_logo.gif" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">
    </div>
    
    <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</body>
</html>


18
사용자의 데이터가 모두 날라가는 것을 막기 위한 저장장치

  • cookie : 클라이언트에게 노출되는 문제가 있음
  • localStorage
  • sessionStorage
  • 데이터베이스

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    var date = new Date();
    //7일동안 보관후 없어짐
    date.setDate(date.getDate() + 7);
    
    var willCookie = '';
    willCookie += 'CookieName = Value;';
    willCookie += 'expires=' +date.toUTCString;
    
    //쿠키저장
    document.cookie = willCookie;
</script>
</head>
<body>

</body>
</html>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<script type="text/javascript">
    alert('쿠키 :' + document.cookie);
</script>

</body>
</html>


19
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    window.onload= function(){
        var result1 = document.getElementById('result1');
        var result2 = document.getElementById('result2');
        
        if(window.localStorage){
            //영구저장소  //개발자 도구에서 지우지 않는한 계속 남아 있음
            result1.innerHTML = 'localStorage 지원';
        }
        if(window.sessionStorage){
            //임시저장소  //브라우저를 껐다가 키면 지워짐
            result2.innerHTML = 'sessionStorage 지원';
        }
        
        
        document.getElementById('btn11').onclick = function(){
            localStorage.key1 = '값1';  //값을 로컬저장소에 저장
        }
        document.getElementById('btn12').onclick = function(){
            result1.innerHTML = 'key1 : '+ localStorage.key1;
        }
        document.getElementById('btn21').onclick = function(){
            sessionStorage.key1 = '값2'; //값을 세션저장소에 저장
        }
        document.getElementById('btn22').onclick = function(){
            result2.innerHTML = 'key1 : '+ sessionStorage.key1;
        }
        
    }
</script>
</head>
<body>

<button id="btn11">localStorage 쓰기</button>
<button id="btn12">localStorage 읽기</button>

<button id="btn21">sessionStorage 쓰기</button>
<button id="btn22">sessionStorage 읽기</button>

<hr />

<div id='result1'></div>
<div id='result2'></div>

</body>
</html>


2016년 7월 28일 목요일

04day Javascript


1
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

</body>
<script type="text/javascript">
    //DOM
    //HTML 태그 <h1></h1> 만듦
    var header =document.createElement('h1');
    //Hello DOM 텍스트 만듦
    var textNode =document.createTextNode('Hello DOM');
    //두개를 연결
    header.appendChild(textNode);  //text를 <h1>에 연결
    document.body.appendChild(header);  //<h1>text</h1>을 <body>에 연결
</script>
</html>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //DOM
    //자바스크립트 태그를 <head> 태그 안에 넣을때는 다른 태그들이 생성되기 전이다. 따라서 window.onload 해줌
    window.onload = function(){
        //HTML 태그 <h1></h1> 만듦
        var header =document.createElement('h1');
        //Hello DOM 텍스트 만듦
        var textNode =document.createTextNode('Hello DOM');
        //두개를 연결
        header.appendChild(textNode);  //text를 <h1>에 연결
        document.body.appendChild(header);  //<h1>text</h1>을 <body>에 연결
    }
</script>
</head>
<body>

</body>
</html>


2
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //DOM
    //클랙했을때 HTML태그를 생성 삽입
    function addTag(){
        var header =document.createElement('h1');
        var textNode =document.createTextNode('Hello DOM');
        header.appendChild(textNode);
        document.body.appendChild(header);
        
        //document.write -- 전체HTML을 지웠다가 다시 만듦
        //appendChild -- 부분 수정
    }
</script>
</head>
<body>

<input type="button" value='tag 추가' onclick='addTag()'>

</body>
</html>


3
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //택스트 노드를 갖지 않는 DOM
    function addTag(){
        var img = document.createElement('img');
        img.src = 'Penguins.jpg';  //태그 속성 추가
        img.width = '500';
        img.height = '350';
        
        document.body.appendChild(img);
    }
</script>
</head>
<body>

<input type="button" value='tag 추가' onclick='addTag()'><br>

</body>
</html>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //택스트 노드를 갖지 않는 DOM
    function addTag(){
        var img = document.createElement('img');
        //img.src = 'Penguins.jpg';  //태그 속성 추가
        //img.width = '500';
        //img.height = '350';
        img.setAttribute('src', 'Penguins.jpg');
        img.setAttribute('width', 500);
        img.setAttribute('height', 350);
        
        //img.data-property = '350' 에러발생 //setAttribute로만 가능
        img.setAttribute('data-property', 350)
        
        document.body.appendChild(img);
    }
</script>
</head>
<body>

<input type="button" value='tag 추가' onclick='addTag()'><br>

</body>
</html>


4
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //innerHTML : 태그노드와 택스트노드를 손쉽게 생성
    //새로작성하기 때문에 원래 <body>태그 안의 정보 사라짐
    function addTag(){
        var output = '';
        output += '<ul>';
        output += ' <li>Javascript</li>';
        output += ' <li>JQuery</li>';
        output += ' <li>Ajax</li>';
        output += '<ul>';
        output += '<img src="Penguins.jpg" width="500">';
        
        document.body.innerHTML = output;
        //document.body.textContent = output;  //HTML태그를 그냥 문자로 인식
    }
</script>
</head>
<body>

<input type="button" value='tag 추가' onclick='addTag()'><br>

</body>
</html>


5
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //innerHTML
    function addTag(){
        var tag = document.body.innerHTML;  //현재 HTML <body>를 읽어옴
        console.log(tag)
    }
</script>
</head>
<body>

<input type="button" value='tag 추가' onclick='addTag()'><br>

<table>
    <tr>
        <td>난 테이블</td>
    </tr>
</table>

</body>
</html>


6
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //getElementById() 특정 태그를 가져옴
    var viewTag = function(){
        var h1 = document.getElementById('header1');
        console.log(h1);  //태그 전체를 문자열로 가져옴
        console.log(h1.innerHTML); //텍스트에 접근
        console.log(h1.textContent);
    }
    var modifyTag = function(){
        var h2 = document.getElementById('header2');
        h2.innerHTML = '<b>Header20</b>';
    }
</script>
</head>
<body>
<h1 id='header1'>Header1</h1>
<h1 id='header2'>Header2</h1>
<input type="button" value='내용보기' onclick='viewTag()'><br>
<input type="button" value='태그수정' onclick='modifyTag()'><br>

</body>
</html>


7
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    * {
    font-family : '맑은 고딕';
    font-size: 10pt
    }
    #t1 td, #t2 td{
    padding: 5px;
    border: 1px solid gray;
    }
</style>
<script type="text/javascript">
    //구구단 만들어서 HTML 수정하기
    function viewGugudan(){
        var start = document.frm.startdan.value;  //시작단 가져오기
        var end = document.frm.enddan.value;      //끝단 가져오기
        
        var output = '<table id="t2">';
        for(var i=start;i<=end;i++){
            output += '<tr>';
            for(var j=1; j<10;j++){
                output += '<td>'+i+' X '+j+' = '+i*j+'</td>';
            }
            output += '</tr>';
        }
        output += '</table>'
        document.getElementById('result').innerHTML = output;
        
    }
</script>
</head>
<body>

<table id='t1'>
<tr>
    <td>
        <form name='frm'>
        시작단 : <input type="text" name='startdan' />~
        끝단 : <input type="text" name='enddan' />
        <input type="button" value='구구단 출력' onclick='viewGugudan()'>        
        </form>
    </td>
</tr>
</table>

<hr />
<div id='result'>결과 : </div>

</body>
</html>


8
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //여러개의 문서 객체를 가져오는 방법
    var viewTag = function(){
        var headers = document.getElementsByTagName('h1');
        console.log(headers);
        console.log(typeof(headers));
        console.log(Array.isArray(headers)); //배열이 아니라고 나오지만 배열처럼 사용할 수 있음
        
        for(var i=0; i<headers.length; i++){
            console.log(headers[i].innerHTML);
        }
    }
</script>
</head>
<body>

<h1>Header1</h1>
<h1>Header2</h1>
<h1>Header3</h1>
<input type="button" value='tag 보기' onclick='viewTag()' />
</body>
</html>


9
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    var viewTag = function(){
        //querySelector 선택자로 가장먼저 선택되는 객체를 가져옴
        //css 문법을 사용해서 태그를 선택할 수 있음
        var header1 = document.querySelector('#header1');
        console.log(header1.innerHTML);
        
        //querySelectorAll 선택자로 선택되는 모든 객체를 배열로 가져옴
        var headers = document.querySelectorAll('#header1');
        console.log(headers[0].innerHTML);
        console.log(headers[1].innerHTML);
    };
</script>
</head>
<body>

<h1 id ='header1'>Header1</h1>
<h1 id ='header1'>Header2</h1>
<input type='button' value='tag 보기' onclick='viewTag()'>

</body>
</html>


10
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    var changeTag = function(){
        //css 수정
        var header1 = document.getElementById('header1');
        header1.style.border = '1px solid red';
        header1.style.color = 'orange';
    };
</script>
</head>
<body>

<h1 id ='header1'>Header1</h1>
<h1 id ='header2'>Header1</h1>
<input type='button' value='style 수정' onclick='changeTag()'>

</body>
</html>


11
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    var removeTag = function(){
        //removeChild  태그 제거
        var div = document.getElementById('div1')
        document.body.removeChild(div);
    };
    var removeTag2 = function(){
        //div 태그안의 h1태그 제거
        var div = document.getElementById('div1')
        var header1 = document.getElementById('header1');
        div.removeChild(header1);
    };
</script>
</head>
<body>
<div id='div1'>
    <h1 id ='header1'>Header1</h1>
    <h1 id ='header2'>Header1</h1>
</div>

<input type='button' value='tag 제거' onclick='removeTag()'>
<input type='button' value='tag 제거2' onclick='removeTag2()'>

</body>
</html>


12
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //고전 이벤트 모델  : 동적 이벤트 추가
    window.onload = function(){
        var h1 = document.getElementById('header');
        h1.onclick =function(){
            alert("click "+this);  //this를 사용하면 이벤트 발생객채 찾을 수 있음
            
            h1.onclick = null;  //이벤트를 제거시킴 //1회성 이벤트 생성
        }
    };
    //인라인 이벤트  : 정적 이벤트
    function clicks(){   //click()은 예약어라서 사용하면 안됨
        alert("click "+this);
    }
</script>
</head>
<body>

<h1 id='header'>click</h1>
<h1 id='header2' onclick='clicks()'>click</h1>
<h1 id='header3' onmousewheel='clicks()'>click</h1>  <!-- on... 여러가지 이벤트가 있음 -->

</body>
</html>


13
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //이벤트 안에서 this 사용
    window.onload = function(){
        document.getElementById('header').onclick = function(){
            this.style.color = 'orange';
            this.style.backgroundColor = 'red';
        }
    }
</script>
</head>
<body>

<h1 id='header'>click</h1>

</body>
</html>


14
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //이벤트 내부의 상황을 보기
    window.onload = function(e){
        //console.log(e);
        document.getElementById('header').onclick = function(e){ //e는 클릭시 자동으로 받는 매개변수
            var result = document.getElementById('result');
            result.innerHTML = '';
            
            /* 이벤트 전체 내용 보기
            for(var key in e){
                result.innerHTML += '<p>'+key+' : '+ e[key]+'</p>';
            } */
            result.innerHTML +='<p>'+e.x+'</p>';  //x좌표
            result.innerHTML +='<p>'+e.y+'</p>';  //y좌표
        }
    }
</script>
</head>
<body>

<h1 id='header'>click</h1>
<div id='result'></div>

</body>
</html>


15
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    window.onload = function(){
        var btn1 = document.getElementById('btn1');
        var btn2 = document.getElementById('btn2');
        
        var count1 = document.getElementById('count1');
        var count2 = document.getElementById('count2');
        
        btn1.onclick = function(){
            count1.innerHTML = Number(count1.innerHTML)+1;
        }
        btn2.onclick = function(){
            count2.innerHTML = Number(count2.innerHTML)+1;
            btn1.onclick();  //이벤트 강제발생 //onclick을 함수처럼 사용할 수 있음
        }
    }
</script>
</head>
<body>

<button id='btn1'>하나 +1</button>
<button id='btn2'>모두 +1</button>
<h1>button1 - <span id='count1'>0</span></h1>
<h1>button2 - <span id='count2'>0</span></h1>

</body>
</html>


16
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //디폴트 이벤트 제거
    window.onload = function(e){
        document.getElementById('frm1').onsubmit = function(){
            //return false;
            //디폴트 이벤트를 제거함으로 비밀번호를 같을경우만 제출하도록 만들 수 있음
            
            var pass1 = document.getElementById('pass').value;
            var pass2 = document.getElementById('pass-check').value;
            
            if(pass1 == pass2){
                alert('동일한 비밀번호')
            }else{
                alert('다른 비밀번호')
                return false;
            }
        }
    }
</script>
</head>
<body>
<!-- action: 입력된 내용을 처리할 웹페이지 -->
<form action="test.jsp" id='frm1'>
    <label for="name">이름</label><br>
    <input type="text" name='name' id='name' /><br>
    <label for='pass'>비밀번호</label><br>
    <input type="password" name='pass' id='pass' /><br>
    <label for='pass-check'>비밀번호 확인</label><br>
    <input type="password" id='pass-check' /><br>
    <input type="submit" value='제출submit' />  <!-- submit에는  페이지 이동 디폴트 이벤트 있음 -->
    <input type="button" value='button' />  <!-- button에는 아무런 이벤트 없음 -->
</form>

</body>
</html>


17
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    * {border:3px solid black;}
</style>
<script type="text/javascript">
</script>
</head>
<body>
    <!-- 이벤트 버블링 : 자식노드에서 부모노드 순으로 이벤트를 실행  -->
    <div onclick="alert('outer-div')">
        <div onclick="alert('inner-div')">
            <h1 onclick="alert('header')">
                <p onclick="alert('pagagraph')">Pagagraph</p>
            </h1>
        </div>
    </div>

</body>
</html>


18
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    * {border:3px solid black;}
</style>
<script type="text/javascript">
    window.onload = function(){
        document.getElementById('header').onclick = function(){
            alert('header');
        }
        //이벤트 전달 막는 방법
        document.getElementById('paragraph').onclick= function(e){
            alert('paragraph')
            
            e.cancelBubble=true;  //인터넷 익스플로러용
            if(e.stopPropagation){ //그외 브라우저용
                e.stopPropagtion();
            }
        }
    }
</script>

</head>
<body>
    <!-- 이벤트 버블링 : 자식노드에서 부모노드 순으로 이벤트를 실행  -->
<h1 id='header'>
    <p id='paragraph'>Pagagraph</p>
</h1>


</body>
</html>


19
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //window.onload = function(){};
    //윈도우익스플로러 이벤트 모델
    window.attachEvent('onload', function(){
        alert('윈도우edge에서는 없어짐');
        var header = document.getElementById('header');
        header.attachEvent('onclick', function(){
            alert('click');
        });
    });
</script>
</head>
<body>

<h1 id='header'>Click</h1>

</body>
</html>


20
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //표준 이벤트 모델 : W3C에서 공식적으로 지정한 DOM Level 2 이벤트 모델
    //             이벤트 캡쳐링을 지원하지만 구현한 프로그램이 아직 없음
    window.addEventListener('load',function(){
        var header = document.getElementById('header');
        header.addEventListener('click', function(){
            alert('click');
        });
        header.addEventListener('mouseout', function(){
            alert('mouseout');
        });
    });
    
</script>
</head>
<body>

<h1 id='header'>Click</h1>

</body>
</html>


21
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //예외처리
    try{
        willException.byeBye();
        alert('try 구문종료');
    }catch (e) {
        alert('Exception 발생');
    }finally{
        alert('finally 실행')
    }
    
</script>
</head>
<body>

</body>
</html>


22
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //예외 메세지 출력
    try{
        var array = new Array(999999999999);
    }catch (exception) {
        var output='';
        for(var i in exception){
            output += i+": "+exception[i] + '\n';
        }
        console.log(output);
    }    
</script>
</head>
<body>

</body>
</html>


23
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //예외 강제 발생 throw
    try{
        throw 'custom exception occur';
    }catch (exception) {
        //자바에서는 catch를 여러개 썼지만 자바스크립트는 if문으로 서로다른 에러를 구분
        if(exception == 'custom exception occur'){
            alert('custom exception occur');
        }else{
            alert('other');
        }
    }
</script>
</head>
<body>

</body>
</html>


24. HTML5 New Elements
http://www.w3schools.com/html/html5_new_elements.asp
자바스크립트에서 HTML태그를 효과적으로 사용하기 위해서 
HTML5에서 새로운 의미론적 태그들이 생김

HTML5 Input Types
http://www.w3schools.com/html/html_form_input_types.asp
input태그에 새로운 속성들이 HTML5에서 생김
인터넷익스플로러에는 지원하지 않는 것이 있으므로 주의 할 것
color
date
datetime
datetime-local
email
month
number
range
search
tel
time
url
week


HTML5 Graphics
http://www.w3schools.com/html/html5_canvas.asp http://www.w3schools.com/html/html5_svg.asp
HTML5에서 그래픽을 처리할 수 있는 태그가 생김
canvas: JavaScript 문법으로 그래픽 처리
svg: SVG 문법으로 그래픽 처리


25
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 
    action : 데이터처리 페이지 (웹프로그램)
    method : 전송방식 (get/post)
        -get: url뒤에 데이터를 싫어서 보냄
            http://localhost:8080/WebEx03/페이지명?변수명=값
            http://localhost:8080/WebEx03/test.jsp?id=aaaaa&passwd=12345
        -post: url에 데이터를 표시 안 함
 -->
<form action='test.jsp' method="get">
아이디 <input type="text" name='id' />
패스워드 <input type="password" name='passwd' />
<input type="submit" value='전송' />
</form>

</body>
</html>


26
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    window.onload = function(){
        //document.getElementById('frm').onsubmit =function(){
        document.getElementById('btn').onclick =function(){  //버튼일 경우 onclick 이벤트
            var query = document.getElementById('query').value;
            if(query.length <=1){
                alert('한자이상 입력해야 합니다.')
                //return false;  //페이지 이동 막음
            }else{
                alert('네이버로 검색합니다')
                document.getElementById('frm').submit(); //버튼일 경우 강제로 submit
            }
        }
    }
</script>
</head>
<body>
<form id='frm' action='https://search.naver.com/search.naver' method="get">
    <!-- hidden 화면에 보이지 않고 전송되는 데이터 -->
    <input type='hidden' name='where' value='nexearch' />
    <input type='hidden' name='sm' value='top_hty' />
    <input type='hidden' name='fbm' value='1' />
    <input type='hidden' name='ie' value='utf8' />
    검색어 <input type="text" name='query' id='query' placeholder='검색어 입력' />
    <!-- <input type="submit" value='네이버 검색' /> -->
    <input type="button" value='네이버 검색' id='btn'/>
</form>

</body>
</html>