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 :)

Dream Big


Use any Linode offering to create something unique or silly in the DEV x Linode Hackathon 2022 and win the Wacky Wildcard category.

β†’ Join the Hackathon <-