Projects

Create Messenger Pop Up ChatBox Type Writer ChatGpt Basic Copy Text Using Tolltip Digital Clock CountDown Timer Create StopWatch FB login from Tab Button Accordion Auto Image Gallery DropDown Menu Modal Box Modal Image Box Scroll Indicator To Do List Autocomplete Remember Search History Toggle Switch Calender Layout Dynamic Calender Alarm Set Password Validation Password Generator Age Calculator Multi Step Form Weather API

Remember Our Search

Note: If you are a beginner, this is something you need to know. Scroll the below section or Click here
  • HTML DOM(querySelector,querySelectorAll etc)
  • appendChild in JS
  • addEventListener in JS

HTML


<div class="showcontent">

    <div class="search-list">
        <input type="text" id="search-input" autocomplete="off">


        <button id="search-btn">Search</button>

        <ul id="suggestions-list">

        </ul>
    </div>

</div>

JavaScript


document.addEventListener("DOMContentLoaded", function () {
    const searchInput = document.getElementById("search-input");

    const searchBtn = document.getElementById("search-btn");
    const suggestionList = document.getElementById("suggestions-list");

    const searchHistory = JSON.parse(localStorage.getItem("searchHistory")) || [];




    //add to search History.
    function addHistory(term) {
        searchHistory.sort();
        if (term && !searchHistory.includes(term)) {
            searchHistory.push(term);
            localStorage.setItem("searchHistory", JSON.stringify(searchHistory));
        }

    }

    searchBtn.addEventListener("click", function () {

        const searchTerm = searchInput.value.trim();
        if (searchTerm.length > 0) {
            addHistory(searchTerm);
            searchInput.value = "";
        }

        //console.log(this);
    });






    //Display the suggestion.
    function displaySuggestion(input) {

        let filterSuggestions = searchHistory.filter((term) => {
            return (term.toUpperCase().includes(input.toUpperCase()));
            //console.log(term);
        });

        if (filterSuggestions.length > 0 && input != "") {
            suggestionList.innerHTML = "";
            filterSuggestions.forEach((term) => {
                suggestionList.style.display = "block";
                console.log(term);
                let li = document.createElement("LI");
                li.textContent = term;
                suggestionList.appendChild(li);
            });

        }
        else {
            suggestionList.style.display = 'none';
        }


        //console.log(filterSuggestions);



    }


    searchInput.addEventListener("input", function () {
        const input = searchInput.value.trim();
        displaySuggestion(input);

    });




    //eventListener for selecting suggesstion.

    suggestionList.addEventListener("click", function (event) {
        console.log(event.target);
        if (event.target.tagName == "LI") {
            searchInput.value = event.target.textContent;

            suggestionList.style.display = "none";
        }
    });


    //Hide suggestion when click outside the suggestion.






});

CSS


.showcontent {
    display: flex;
    justify-content: center;
    position: relative;
}

.search-list {
    display: flex;
    justify-content: center;
    flex-direction: column;
    width: 300px;
}

.search-list input,
.search-list button {
    padding: 8px 16px;
    font-size: 18px;

}

.search-list button {
    background-color: dodgerblue;
    margin-top: 5px;
    border: none;
    color: white;
    cursor: pointer;
}

.search-list button:hover {
    opacity: 0.8;
}

#suggestions-list {
    position: absolute;
    top: 40px;
    background-color: #f4f4f4;
    min-height: 150px;
    overflow-y: auto;
    height: auto;
    width: 300px;
    z-index: 10;

    padding: 0;
    list-style: none;
    display: none;
}

#suggestions-list li {
    padding: 10px;
    border: 1px solid #ccc;
    cursor: pointer;
}

#suggestions-list li:hover {
    background-color: #ccc;
}

new Date()

  • Returns a Date object with the current date and time based on the system's clock.
  • This create a date object represent the current date and time.

toString()

  • The toString() method converts any data type into a string. Syntax: varname.toString(),

padStart()

  • It is used to JS to pad the current string with another string untill the resulting string reaches the given length.
    Example: str.padStart(len,char or string);

setInterval()

  • This method in JS repeatedly calls a function or executes a code with a fixed time delay between each call.

setTimeout()

  • This method is used to execute a function or code snippet after a specified delay in milliseconds.

date.get....()

  • getDate(): Returns the day of the month(1-31)
  • getMonth(): Returns the month(0-11)
  • getFullYear(): Returns the year(4 digit year)
  • getDay(): Returns the day of the week(0-6)
  • getHours(): Returns the hours(0-23)
  • getMinutes(): Returns the minites(0-59)
  • getSeconds(): Returns the seconds(0-59)
  • getMilliseconds(): Returns the milliseconds(0-999)
  • getTime(): Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC