DEV Community

loading...
Cover image for Searching info from Cards using jQuery

Searching info from Cards using jQuery

KhaledtheDev
long life learner Software Developer, serving various types of development and educational services in programming.
・Updated on ・6 min read

alert("Hello Devs!"), the following image is the Favatar web app that we will build together:

Alt Text

The Favatar web app views all the avatars you would like to follow. Each avatar has his own data such as: id, name, job, age and image. Our primary goal in this web app is to be able to search for our avatar by name or job or age, all cards that has one of its data matching the search input will be displayed otherwise they disappear.
To start with:

  1. install visual studio code from the following URL: "https://code.visualstudio.com/download".
  2. install an extension from visual studio code called Live Server by Ritwick Dey.

You can download this web app source code from my GitHub, here is the URL:

Now lets start with some coding!

First of all, these avatars are rendered dynamically in the html using AJAX in jQuery. So what is AJAX? AJAX (Asynchronous JavaScript And XML) is used to request data from a web server (using browser built-in XMLHttpRequest object) and display the data or use the data for a specific purpose (using JavaScript and HTML DOM).

Brief definitions for:
πŸ”΅ XML (eXtensible Markup Language): XML was designed to store data and transport data.
πŸ”΅ HTML DOM (Document Object Model): Document Object Model is a cross-platform and language-independent interface that treats an XML or HTML document as a tree structure wherein each node is an object representing a part of the document.
πŸ”΅ JSON (JavaScript Object Notation): JSON is a lightweight format for storing and transporting data. JSON is often used when data is sent from a server to a web page.

Lets create our JSON file to get data!
json object is written in the following format:

"id":"1"
Enter fullscreen mode Exit fullscreen mode

Where the "id" is the key and "1" is the value. For example we want to search for the avatar that has id = 1, so we search for this avatar based on the key that has value = 1 which is in this case the "id" key.

View JSON File
[
    {
        "id": "1",
        "name": "Mark",
        "age": "26",
        "work": "Actor",
        "img": "https://avataaars.io/?avatarStyle=Circle&topType=Hat&accessoriesType=Prescription02&hairColor=Platinum&facialHairType=MoustacheMagnum&facialHairColor=Red&clotheType=Hoodie&clotheColor=White&graphicType=Bat&eyeType=Wink&eyebrowType=Default&mouthType=Twinkle&skinColor=Light"
    },
    {
        "id": "2",
        "name": "Sarah",
        "age": "24",
        "work": "Physical Therapist",
        "img": "https://avataaars.io/?avatarStyle=Circle&topType=LongHairStraight&accessoriesType=Blank&hairColor=BrownDark&facialHairType=Blank&clotheType=BlazerShirt&eyeType=Default&eyebrowType=Default&mouthType=Default&skinColor=Light"
    },
    {
        "id": "3",
        "name": "Raj",
        "age": "21",
        "work": "Programmer",
        "img": "https://avataaars.io/?avatarStyle=Circle&topType=Turban&accessoriesType=Prescription01&hatColor=PastelOrange&hairColor=BrownDark&facialHairType=MoustacheFancy&facialHairColor=Red&clotheType=CollarSweater&clotheColor=Blue03&eyeType=Happy&eyebrowType=AngryNatural&mouthType=Disbelief&skinColor=Brown"
    },
    {
        "id": "4",
        "name": "Bob",
        "age": "40",
        "work": "Plumber",
        "img": "https://avataaars.io/?avatarStyle=Circle&topType=WinterHat1&accessoriesType=Prescription01&hatColor=Pink&hairColor=Platinum&facialHairType=BeardMagestic&facialHairColor=Brown&clotheType=Overall&clotheColor=Black&eyeType=EyeRoll&eyebrowType=RaisedExcitedNatural&mouthType=Smile&skinColor=Yellow"
    },
    {
        "id": "5",
        "name": "Zack",
        "age": "37",
        "work": "Technical Support",
        "img": "https://avataaars.io/?avatarStyle=Circle&topType=WinterHat2&accessoriesType=Wayfarers&hatColor=Heather&facialHairType=MoustacheMagnum&facialHairColor=Auburn&clotheType=BlazerShirt&eyeType=Surprised&eyebrowType=FlatNatural&mouthType=Smile&skinColor=Pale"
    },
    {
        "id": "6",
        "name": "John",
        "age": "24",
        "work": "Accountant",
        "img": "https://avataaars.io/?avatarStyle=Circle&topType=WinterHat4&accessoriesType=Prescription01&hatColor=Blue03&facialHairType=Blank&facialHairColor=BlondeGolden&clotheType=BlazerSweater&clotheColor=PastelOrange&eyeType=Cry&eyebrowType=RaisedExcitedNatural&mouthType=Disbelief&skinColor=Tanned"
    }
]
Enter fullscreen mode Exit fullscreen mode

View HTML File
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--Document icon -->
    <link rel="shortcut icon" href="avatardefault_92824.png" type="image/x-icon">
    <!--my style file-->
    <link rel="stylesheet" href="index.css">
    <!--jquery cdn to write jquery-->
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
    <!--ajax cdn to get the data from the web server-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!--font awesome cdn-->
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
    <!--my javascript file-->
    <script src="index.js"></script>
    <title>Favatar</title>
</head>
<body>
    <!-- Main container -->
    <div class="container">
        <!-- Seacrh bar container -->
        <div class="searchData">
            <!-- Search bar input and icon inside label-->
            <label>
                <!-- Search input-->
                <input type="text" name="searchData" id="search-input" placeholder="Search for Favatar">
                <!-- Search icon-->
                <i class="fas fa-search"></i>
            </label>
        </div>
        <!-- the div with the id="demo" is where the cards will be rendered dynamically from the JSON file -->
        <div id="demo"></div>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

View CSS File
*{box-sizing: border-box;}

body{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    background-color: #efefef;
}

/*Main container that contains the search bar and the cards*/
.container{
    position: absolute;
    width: 80%;
    height: 90%;
    top: 50%;
    left: 50%;
    display: grid;
    grid-template-rows: 10% 90%;
    justify-items: center;
    transform: translate(-50%,-50%);
}

/* search bar container*/
.container .searchData{
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

/* label contains text input and the search icon*/
.container label{
    width: 60%;
    height: 70%;
    display: flex;
    align-items: center;
}

/* search input*/
.container input{
    width: 100%;
    height: 100%;
    font-size: 1.3rem;
    padding: 0.5rem 1rem;
    padding-left: 2.7rem;
    background-color: white;
    border: none;
    outline: none;
    border-radius: 5px;
    border: 2px solid transparent;
    transition: 0.3s;
}

/* search input on hover and focus chaging border color*/
.container input:hover,
.container input:focus{
    border: 2px solid #65C9FF;
}

/* positioning icon inside the search bar*/
.container label i{
    position: absolute;
    font-size: 1.3rem;
    margin-left: 1rem;
    color: #757575;
    pointer-events: none;
}

/* cards container*/
#demo{
    width: 100%;
    height: 100%;
    padding: 1rem 1rem;
    display: grid;
    grid-template-columns: repeat(3,calc(100% /3));
    justify-items: center;
    box-sizing: border-box;
    overflow-y: scroll;
}

/* changing scrollbar style*/
#demo::-webkit-scrollbar{
    width: 10px;
    background-color: white;
    opacity: 0;
    border-radius: 15px;
}

/* changing scrollbar thumb which is the grey part that we hold and slide down or up*/
#demo::-webkit-scrollbar-thumb{
    background-color: #65C9FF;
    border-radius: 15px;
}

/* styling the card*/
#demo .card{
    width: 80%;
    height: calc(100vh / 1.7);
    margin: 9px;
    background-color: #65C9FF;
    margin-bottom: 2rem;
    border-radius: 10px;
    overflow: hidden;
    transition: 0.5s;
}

/* scale up the card on hover*/
#demo .card:hover{
    box-shadow: 0px 0px 7px rgba(0, 0, 0, 0.5);
    transform: scale(1.05);
}

/* styling the image container*/
#demo div .imageContainer{
    width: 100%;
    height: 60%;
    margin: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom-left-radius: 50% 10%;
    border-bottom-right-radius: 50% 10%;
    background-color: white;
    box-shadow: 0px 2px 4px rgba(0,0,0,0.2);
}

/* specifying the width of the image*/
#demo div .imageContainer img{
    width:50%;
}

/* styling details container which contains the name, work and age*/
#demo div .details{
    max-width: 100%;
    height: 40%;
    margin: 0;
    display: grid;
    justify-items: center;
    align-items: center;
    grid-row: auto;
    grid-row-gap: 0.3rem;
    text-align: center;
    padding: 0.5rem;
}

/* removing margins from all p in the details container*/
#demo div .details p{
    margin: 0;
}

/* specifying font size for first p (name)*/
#demo div .details p:first-child{
    font-size: 1.6rem;
}

/* specifying font size for second p (work)*/
#demo div .details p:nth-child(2){
    font-size: 1.3rem;
}

/* specifying font size for third p (age)*/
#demo div .details p:nth-child(3){
    font-size: 1.1rem;
}

/* styling follow button*/
#demo div .details button{
    width: 50%;
    font-size: 1rem;
    padding: 0.5rem 1rem;
    border: 3px solid white;
    background-color: white;
    color: #65C9FF;
    font-weight: 700;
    cursor: pointer;
    transition: 0.3s;
}

/* change the button style on hover*/
#demo div .details button:hover{
    background-color: #65C9FF;
    color: white;
}
Enter fullscreen mode Exit fullscreen mode

Now is the most important part of this project, the JavaScript file! Lets get deep into details!
1- The best practice to write jQuery in JavaScript file is to start with:

$(document).ready(function(){

})
Enter fullscreen mode Exit fullscreen mode

2- The next step is we will define a variable named myData to store the data object in it, then we will create a new XMLHttpRequest() in order to get the data store in JSON file from the web server. The following code should be implemented inside the above function

var myData;
    // *1
    var xmlhttp = new XMLHttpRequest();
    //*2
    xmlhttp.onreadystatechange = function () {
        //*3
        if (this.readyState == 4 && this.status == 200) {
            //*4
            myData = JSON.parse(this.responseText);
            //*5
            myData.forEach(data => {
                //*6
                $("#demo").append("<div class='card' id='"+data.id+"'>"+
                "<div class='imageContainer'><img src='"+ data.img +"'></div>"+
                "<div class='details'><p>"+data.name+"</p><p>"+data.work+"</p><p>"+data.age+"</p><button type='button'><i class='fas fa-plus'></i> Follow</button></div></div>"
                )
            });
        }
    };
    //*7
    xmlhttp.open("GET", "data.json", true);
    //*8
    xmlhttp.send();
Enter fullscreen mode Exit fullscreen mode

Now let us explain the above code in details!

1- First:

We create a XMLHttpRequest() and store it in var xmlhttp. So what is XMLHttpRequest()? It is an object that can be used to request data from a web server. XMLHttpRequest() object is also used for the following purposes:

  1. Update a web page without reloading the page.
  2. Request data from a server -after page has loaded.
  3. Receive data from a server -after the page has loaded.
  4. Send data to a server -in the background.

Discussion (0)