DEV Community

Dahye Ji
Dahye Ji

Posted on

jQuery, Ajax, Axios

jQuery

jQuery is JavaScript library.
jQuery CDN: https://code.jquery.com/
jQuery CDN
You can check from the latest version. If you click one of the links, you can get the CDN link for jQuery. I used minified for jQuery 3.x
Copy and paste the link inside the head tag in html file(and it should be above your css link). Because it's read from top to bottom - if your css link is above the jQuery link, your css might not work like you expected.

 <!-- jQuery CDN: https://code.jquery.com/ -->
 <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script>
Enter fullscreen mode Exit fullscreen mode

jQuery documentation

Read Documentation: https://api.jquery.com/
You can find anything you'd like to do with jQuery if you use search box. It shows you how to use jQuery with examples.

Selector

You can select elements with id, class and tag name like you do in css but you should use dollar sign and parentheses $()
For example, if you'd like to select an element with id name "item", $("#item"). If the element has class "box", then $(".box") and for h2 tag, $("h2").
(If it was javascript you have to write like document.querySelector("#item") or document.getElementByID("item") which is very long.)

  • .parent(): gets the ancestors of each element in the current set of matched elements, optionally filtered by a selector. Usage eg) $('.items').parent().css('backgroundColor', 'blue');
  • .children(): gets the children of each element in the set of matched elements, optionally filtered by a selector. Usage eg) $('.ul2').children('li:gt(5)').css('color', 'blue').css('backgroundColor', 'red')
  • .siblings() gets the siblings of each element in the set of matched elements, optionally filtered by a selector.

Using jQuery

  • .html(): is used to set an element's content. It's to write html.
  • .css(): as a setter, jQuery modifies the element's style property. For example, $("#mydiv").css("color", "green") is equivalent to document.getElementById("mydiv").style.color = "green".
  • .attr(): a convenient way to set the value of attributes
  • val(): allows you to pass an array of element values

jQuery filter

  • :eq: equal( = ) $("li").eq(2).css("color", "blue" ); means change color to blue for li element on the index 2.
  • :lt: little ( < ), stands for the less-than sign $("li:lt(2)") means li elements that have smaller index than 2.
  • :gt: greater ( > ), stands for the greater-than sign $("li:gt(4)").css( "backgroundColor", "yellow"); means change background color to yellow for li elements that have greater index than 4.
  • :not(selector): $("input:not(:checked)+span").css("backgroundColor", "yellow"); means change background color to yellow for the span that is next to input not checked.
  • :even: even elements in that set.
  • :odd: odd elements in that set.
  • :first: the first element in that set.
  • :last: the last element in that set
// example
$( "li" ).filter(":nth-child(2n)").css("backgroundColor", "red" );
Enter fullscreen mode Exit fullscreen mode

filter by attribute

  • attributeContains - input[name*="name"]: It will select an element if the selector's string appears anywhere within the element's attribute value. Usage eg) $("input[name*='man']").val("has man in it!");
  • attributeEquals - input[name="value"]: Selects elements that have the specified attribute with a value exactly equal to a certain value. Usage eg) $("input[value='Hot Fuzz']").next().text("Hot Fuzz");

child filter

  • :first-child: first-child selector can match more than one. one for each parent. This is equivalent to nth-child(1).
  • :last-child: selects all elements that are the last child of their parent. last-child selector can match more than one. one for each parent.
  • :nth-child(2): implementation of :nth- selectors is strictly derived from the CSS specification, the value of n is "1-indexed", meaning that the counting starts at 1
  • :nth-child(even): even number indexed elements
  • :nth-child(odd): odd number indexed elements

content filter

  • :contains(text): select all elements that contain the specified text. Usage eg) $("div:contains('shop')").css("text-decoration", "underline");
  • :empty: removes all child nodes of the set of matched elements from the DOM. Usage eg) $(".hello").empty();
  • :has(selector): selects elements which contain at least one element that matches the specified selector

class attribute

  • .addClass() : adds the specified class(es) to each element in the set of matched elements.
  • .removeClass() : remove a single class, multiple classes, or all classes from each element in the set of matched elements.
  • .toggleClass() : add or remove one or more classes from each element in the set of matched elements, depending on either the class’s presence or the value of the state argument.
  • .hasClass() : determine whether any of the matched elements are assigned the given class.

editing with jQuery

$("p").append("Some appended text.");
$("p").prepend("Some prepended text.");
$("#div1").remove();
$('ul').after('<h2>The end!</h2>');
$('ul').before('<h2>Start!</h2>')
$("div").addClass("important");
$("h1,h2,p").removeClass("blue");
$("h1,h2,p").toggleClass("blue");

$("p").css("background-color");
$("p").css("backgroundColor","yellow");
// You can use - and camelCase but it's good to use one fixed.
Enter fullscreen mode Exit fullscreen mode

effects with jQuery

$("p").hide();
$("p").show();
$("p").toggle();
$("#div1").fadeIn();
$("#div1").fadeOut();
$("#div1").fadeToggle();
$("#div3").fadeIn(3000); 
Enter fullscreen mode Exit fullscreen mode

jQuery practice

<!DOCTYPE html>
<html lang="ko">

<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>
    <!-- https://code.jquery.com/ -->
    <!-- 3점대 minified 사용함 -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script>
        // 문사가 다 준비되면 실행.
        $(function () { // 이것을 주석처리하면 실행이 안됩니다.
            //html이 다 로드되지 않은 상태이기 떄문에 그렇습니다.
            $('box').fadeOut(3000).fadeIn(3000);
        })
    </script>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: palevioletred;
        }

        .box2 {
            width: 100px;
            height: 100px;
            opacity: 0.3;
            background-color: red;
        }
    </style>
</head>

<body>
    <h1 id="one">jQuery 실습</h1>
    <p>hello</p>
    <button class="btn1">클릭해!!</button>
    <p class="실습">jQuery 실습을 하고 있습니다.</p>
    <img>
    <br>
    <textarea name="메모장" id="메모장" cols="30" rows="10"></textarea>
    <button class="btn2">메모장 내용 경고창으로 출력</button>
    <p id="p3">hello world</p>
    <!-- 
        1. li items 부모를 찾아 background-color를 파란색으로 버꿔주세요.
        2. items 2번째 색을 빨간색으로 바꿔주세요.
        3. ul2의 자식인 li요소를 선택하여 1번부터 3번까지 color를 녹색으로 바꿔주세요.
        4. ul2의 자식인 li요소를 선택하여 7번부터 10번까지 color를 파란색, background-color를 빨간색으로 바꿔주세요.
     -->
    <div class="wrapper">
        <h1 class="title">TITLE</h1>
        <ul>
            <li class="items">item1</li>
            <li class="items">item2</li>
            <li class="items">item3</li>
        </ul>
    </div>
    <!-- ul>li{hello}*10 -->
    <ul class="ul2">
        <li>hello</li>
        <li>hello</li>
        <li>hello</li>
        <li>hello</li>
        <li>hello</li>
        <li>hello</li>
        <li>hello</li>
        <li>hello</li>
        <li>hello</li>
        <li>hello</li>
    </ul>
    <div id="div1">Hello world!</div>
    <div class="one blue">hello world</div>
    <div class="two blue">hello world</div>
    <p class="blue">hello world</p>
    <div class="three">hello</div>
    <div class="three blue">hello</div>
    <div class="box">hello world</div>
    <div class="box2">hello world</div>
    <button class="btn3">눌러봐요!</button>
    <script>
        // document.getElementById('one').innerHTML = "!!!";
        // class는 . 아이디는 #
        $('#one').text('hello jquery');
        // $('p').hide(); // display: none 됨
        $('.btn1').click(function () {
            alert('클릭했네요?');
        });
        // $('.실습').text('<strong>실습</strong>중이에요');
        $('.실습').html('<strong>실습</strong>중이에요');
        $('.실습').css('color', 'red');
        $('.실습').css('backgroundColor', 'blue');

        // camelCase is used in jQuery
        $('img').attr('src', '../html/img/a.jpg',);
        $('img').attr('data-name', '프로필').attr('data-hello', 'world');
        $('img').css({ 'width': '400px', 'height': '280px' });

        $('.btn2').click(function () {
            let 메모장값 = $('#메모장').val();
            $('#메모장').val('값을 입력하세요.');
            alert(메모장값);
        });
        $('#p3').css('color', 'red').css('backgroundColor', 'blue');

        $('.items').parent().css('backgroundColor', 'blue');
        $('.items').eq(1).css('color', 'red');
        // $('.ul2 > li:lt(3)').css('color', 'green');
        // $('.ul2').children('li:lt(3)').css('color', 'green');
        $('.ul2:nth-child(n+3)').css('color', 'green')
        // $('.ul2 > li:gt(5)').css('color', 'blue').css('backgroundColor', 'red');
        $('.ul2').children('li:gt(5)').css('color', 'blue').css('backgroundColor', 'red')

        // append는 마지막에 추가됨 
        // 홑따옴포, 쌍타옴표는 JSON에서만 주의하면 되고 아무거나 사용해도 되긴함.(보통 회사 컨벤션에 맞게 사용)
        // ul 복수개를 잡음!
        $('ul').append("<li>hello world end</li>");
        // append는 앞에 추가됨  (ul의 자식에 추가)
        $('ul').prepend("<li>hello world start</li>");
        // after는 ul 다음에 추가
        $('ul').after("<h2>끝!</h2>");
        $('ul').before("<h2>시작</h2>");
        // this removes the element
        // $('#div1').remove()
        $('#div1').addClass('important');
        $('.one, .two, p').removeClass('blue');
        // toggle은 없으면 생기고 있으면 없어지게
        $('.three').toggleClass('blue');
        // 모달창에서 사용한 사례가 있음
        $('.box').fadeOut(3000).fadeIn(3000);
        https://electronic-moongchi.tistory.com/75
        $('.box').click(function () {
            $(this).stop();
        });
        // div 클릭했을 때 안 보이게 하기
        // dom이 준비되면 실행해라!
        $(function () {
            $('.box').click(function () {
                $(this).hide();
            });
        });
        //JQuery - animate
        //버튼 클릭했을 때 변화주기
        $('.btn3').click(function () {
            $('.box2').animate({
                width: '300px',
                height: '300px',
                opacity: 1,
            }, 'slow');
        });

        $(".box2").hover(function () {
            $(this).css("background-color", "yellow");
        }, function () {
            $(this).css("background-color", "blue");
        });

        $('.box2').mouseenter(function () {
            alert("You entered!");
        });
        $('.box2').mouseleave(function () {
            alert("Bye! You now leaved");
        });
    </script>

</body>

</html>
Enter fullscreen mode Exit fullscreen mode

hover()

<div id="box"></div>
Enter fullscreen mode Exit fullscreen mode
// hover - change color(when hover, background color to yellow, when it's not hover than blue)
$("#box").hover(function(){
  $(this).css("background-color", "yellow");
}, function(){
  $(this).css("background-color", "blue");
});
Enter fullscreen mode Exit fullscreen mode

mouse event

$("#p1").mouseenter(function(){
    alert("You entered p1!");
});
$("#p1").mouseleave(function(){
    alert("Bye! You now leaved p1!");
});
Enter fullscreen mode Exit fullscreen mode

jQuery plugins

Ajax (Asynchronous Javascript and XML)

Find more about Ajax

  $('#btn_data').click(function () {
            $('#data').load('https://testtest/main/data/data.json');
        });

        $('#btn_data2').click(function () {
            $("#data2").load('https://testtest/main/index.html h1');
        });

        $('#btn_data3').click(function () {
            $("#data3").load('https://testtest/main/index.html h1', function (responseText, statusText, xhr) {
                console.log(responseText);
                console.log(statusText);
                console.log(xhr);
                console.log(xhr.status);
            }
            );
        });

        $('#btn_data4').click(function () {
            //$.ajax({route, sync status, things to do when it succed})
            //$.ajax({url:'route', async: false, success:function(result){}})
            $.ajax({
                url: 'https://testtest/main/index.html',
                async: true,
                success: function (result) {
                    $("#data4").html(result);

                }

            });
        });
Enter fullscreen mode Exit fullscreen mode

Axios

Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and node.js with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.

const url = 'https://raw.githubusercontent.com/paullabkorea/coronaVaccinationStatus/main/data/data.json';
        axios.get(url).then((response) => { console.log(response) });
Enter fullscreen mode Exit fullscreen mode

https://axios-http.com/docs/intro
Learn about Axios

(I learnt about Ajax and Axios briefly, will write detailed post when I learn node.js later)

Top comments (2)

Collapse
 
bogdanbatsenko profile image
bogdanbatsenko

jQuery is a controversial topic. I am self-taught developer. I struggled hard learning vanilla JS, neglecting jQuery. Strange as it may seem, I know Vanilla JS better than jQuery. Now I got offer from a company and they asked if I knew jQuery. Your post is exactly on time.

Collapse
 
daaahailey profile image
Dahye Ji

I heard that jQuery is used less than before but there are many places still using it. I personally prefer Vanilla JS than jQuery since it was first time for me to use it and it was more confusing to me but I think it's better if you know both anyways :)