This content originally appeared on Level Up Coding - Medium and was authored by Jessica Lee
I am doing an Instagram cloning project using Vanilla JS, and this post is about creating a search bar. Instagram has a search bar that moves its placeholder and an icon when clicked, and generates a cancel (X) icon at the right side of the search box. Images are provided here:
There should be many other ways that may be more efficient, but I am mainly focusing on getting familiar with the main methods in JS.
const searchIcon = document.getElementById(“search-icon”);
const searchInput = document.getElementById(“search-input”);
const cancelIcon = document.getElementById(“cancel-icon”);
searchInput.addEventListener(“click”, moveSearchBarElements);
function moveSearchBarElements() {
searchIcon.id = “search-icon-moved”;
searchInput.id = “search-placeholder-moved”;
cancelIcon.id = “cancel-icon-enabled”;
document.addEventListener(
“click”,function (e) {
const isClickedInside = searchInput.contains(e.target);
if (!isClickedInside) {
searchIcon.id = “search-icon”;
searchInput.id = “search-input”;
cancelIcon.id = “cancel-icon”;
searchInput.value = “”;
}
});
}
- Firstly, I had to set variables for HTML elements — search-icon, search-input, and cancel-icon. Here, I have the id attributes, but class may be better there are multiple elements to be shared the same class.
- So, we are changing the look of the search bar when “clicked”. Therefore we need addEventListener() with "click" and the following function moveSearchBarElements to be executed.
- When clicked, moveSearchBarElements function is executed. Firstly, I changed the three variables’ ids. The changed ids — search-icon-moved, search-placeholder-moved, and cancel-icon-enabled all have their css properties set in css file. By changing them to these ids, their positions, display, etc will be applied.
- Then, I added another addEventListener to delete search values in the search input and make the search bar elements (icons, placeholder) go back to their initial positions once clicked outside of the search input. This one has a parameter of e or event as we need to check if the target of the event (click) was inside of the search input. Then, I added if statement that if it is NOT clicked inside the input, the elements’ ids go back to what they were before the input was clicked, and the searchInput.value is set to empty.
Create A Search Bar using Vanilla JS was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Jessica Lee
Jessica Lee | Sciencx (2021-03-29T14:44:22+00:00) Create A Search Bar using Vanilla JS. Retrieved from https://www.scien.cx/2021/03/29/create-a-search-bar-using-vanilla-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.