JS/JavaScript

#25 자바스크립트 jQuery, Ajax, 에니메이션

인생아 2024. 9. 8. 11:30
반응형

1. jQuery란?

jQuery는 JavaScript 라이브러리로, 웹 개발자들이 JavaScript를 더욱 쉽게 작성할 수 있도록 도와주는 도구입니다. HTML 문서 탐색, 이벤트 처리, 애니메이션, Ajax 처리 등을 간단한 API로 지원하여, 복잡한 JavaScript 코드를 간결하게 작성할 수 있습니다.

주요 특징:

  • 크로스 브라우저 호환성: jQuery는 다양한 브라우저에서 일관된 동작을 보장합니다.
  • 코드 간소화: 긴 JavaScript 코드를 짧고 간결하게 작성할 수 있습니다.
  • 플러그인 확장성: 수많은 jQuery 플러그인이 있어 다양한 기능을 쉽게 추가할 수 있습니다.

2. jQuery의 기본 사용법

jQuery를 사용하기 위해서는 먼저 jQuery 라이브러리를 HTML 파일에 포함해야 합니다. 일반적으로 CDN(Content Delivery Network)을 통해 라이브러리를 포함합니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Hello, jQuery!</h1>
</body>
</html>

이 코드는 jQuery 라이브러리를 웹 페이지에 추가하는 기본적인 방법입니다. 이렇게 하면 jQuery의 다양한 기능을 사용할 수 있습니다.

3. jQuery 선택자 (Selectors)

jQuery의 가장 강력한 기능 중 하나는 **선택자(Selectors)**입니다. HTML 요소를 선택하고 조작하는 데 사용됩니다. CSS 선택자를 기반으로 동작하며, 다양한 방식으로 HTML 요소를 선택할 수 있습니다.

a. 태그 선택자

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Selector Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p").css("color", "blue");
        });
    </script>
</head>
<body>
    <p>이 텍스트는 파란색으로 바뀝니다.</p>
</body>
</html>

이 예제에서는 페이지에 있는 <p> 태그를 선택하여 글자 색상을 파란색으로 변경합니다.

b. 클래스 선택자

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Class Selector Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $(".myClass").css("font-size", "20px");
        });
    </script>
</head>
<body>
    <p class="myClass">이 텍스트의 크기는 20px로 설정됩니다.</p>
</body>
</html>

여기서는 class="myClass"인 요소만을 선택해 글자 크기를 20px로 변경합니다.

c. 아이디 선택자

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery ID Selector Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#myId").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <p id="myId">이 요소의 배경색은 노란색으로 변경됩니다.</p>
</body>
</html>

이 예제에서는 id="myId"인 요소의 배경색을 노란색으로 변경합니다.

4. jQuery 이벤트 처리

jQuery는 다양한 이벤트를 쉽게 처리할 수 있게 해줍니다. click(), hover() 같은 메서드로 간편하게 이벤트를 설정할 수 있습니다.

a. click() 이벤트

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Click Event Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                alert("버튼이 클릭되었습니다!");
            });
        });
    </script>
</head>
<body>
    <button id="btn">클릭하세요!</button>
</body>
</html>

위 예제에서는 버튼을 클릭하면 경고창이 뜨도록 설정했습니다.

b. hover() 이벤트

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Hover Event Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#hoverMe").hover(function(){
                $(this).css("color", "red");
            }, function(){
                $(this).css("color", "black");
            });
        });
    </script>
</head>
<body>
    <p id="hoverMe">마우스를 이 텍스트 위에 올려보세요!</p>
</body>
</html>

여기서는 텍스트 위에 마우스를 올리면 색상이 빨간색으로 바뀌고, 다시 내리면 검은색으로 돌아갑니다.

5. jQuery 애니메이션

jQuery는 간단한 애니메이션 효과도 제공합니다. show(), hide(), fadeIn(), slideUp() 등의 메서드를 이용하면 HTML 요소를 애니메이션으로 표시하거나 숨길 수 있습니다.

a. fadeIn()과 fadeOut()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Fade Animation Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#fadeOutBtn").click(function(){
                $("#box").fadeOut();
            });

            $("#fadeInBtn").click(function(){
                $("#box").fadeIn();
            });
        });
    </script>
</head>
<body>
    <button id="fadeOutBtn">페이드 아웃</button>
    <button id="fadeInBtn">페이드 인</button>
    <div id="box" style="width:100px;height:100px;background-color:blue;"></div>
</body>
</html>

위 예제에서는 버튼을 클릭하면 파란색 상자가 fadeOut()으로 사라지고, fadeIn()으로 다시 나타납니다.

b. slideUp()과 slideDown()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Slide Animation Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#slideUpBtn").click(function(){
                $("#panel").slideUp();
            });

            $("#slideDownBtn").click(function(){
                $("#panel").slideDown();
            });
        });
    </script>
</head>
<body>
    <button id="slideUpBtn">슬라이드 업</button>
    <button id="slideDownBtn">슬라이드 다운</button>
    <div id="panel" style="width:200px;height:100px;background-color:green;">슬라이드 패널</div>
</body>
</html>

여기서는 버튼을 눌러 녹색 패널을 슬라이드 업 및 다운으로 숨기거나 표시할 수 있습니다.

6. jQuery Ajax

Ajax는 웹 페이지를 다시 로드하지 않고도 서버와 통신할 수 있게 해줍니다. jQuery의 $.ajax() 메서드를 사용하면 서버로 데이터를 보내거나 받아올 수 있습니다.

a. Ajax 요청 예제

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Ajax Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#loadDataBtn").click(function(){
                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    type: "GET",
                    success: function(data) {
                        $("#result").text(data.title);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="loadDataBtn">데이터 불러오기</button>
    <p id="result">데이터가 여기에 표시됩니다.</p>
</body>
</html>

위 예제에서는 버튼을 클릭하면 Ajax를 통해 JSON 데이터를 서버로부터 불러와 페이지에 출력합니다.

결론

jQuery는 웹 개발에서 복잡한 JavaScript 코드를 간결하게 작성할 수 있도록 도와주는 강력한 라이브러리입니다. 선택자, 이벤트 처리, 애니메이션, Ajax 기능을 사용하여 인터랙티브하고 동적인 웹 페이지를 쉽게 만들 수 있습니다.

반응형