With HTML, CSS and JS I've made an expanding search bar, but I don't really know how to close it again.
My HTML code is very simple as I'm just testing how to make a search bar.
<div class="search-contain">
<i class="search fa fa-search" id="search-btn"></i>
<input type="text" id="search" placeholder="">
</div>
The styling isn't really important so here is my JS so far:
const searchBtn = document.getElementById('search-btn'); /*From the icon*/
const search = document.getElementById('search'); //From input
searchBtn.addEventListener('click', () => { //Expanding
search.style.width = '80%';
search.style.paddingLeft = '60px';
search.style.cursor = 'text';
search.focus();
typewriter();
})
//Effect on the placement of text
var i = 0;
var message = 'Semesterfest';
var speed = 100; //The higher the slower
function typewriter(){
if(i < message.length){
msg = search.getAttribute('placeholder') + message.charAt(i);
search.setAttribute('placeholder', msg);
i++;
setTimeout(typewriter, speed);
}
}
It's working so far, the bar is expanding when I press the search icon, it focuses on the input field and my typewriter effect is smooth.
But I can't make it close so it's not expanded anymore. It won't go back to the starting state
I'll be honest and say I haven't tried much, I'm very new to JS so I don't have the best idea of what I can do when I run into trouble. I've read somewhere that jQuery might help but I've never used it so I just sticking to plain JS
The icon was not there so I made a button
when you click first it will expand and when you will click the second time it will collapse,
const searchBtn = document.querySelector('#search-btn');
const search = document.getElementById('search'); //From input
let index =true ;
searchBtn.addEventListener('click', () => { //Expanding
index ? search.style.width = '80%' : search.style.width = '20%' ;
index ? search.style.paddingLeft='60px' :search.style.paddingLeft = '20px';
search.style.cursor = 'text';
search.focus();
typewriter();
index ? index = false : index = true;
})
var i = 0;
var message = 'Semesterfest';
var speed = 100;
let msg;
function typewriter(){
if(i < message.length){
msg = search.getAttribute('placeholder') + message.charAt(i);
search.setAttribute('placeholder', msg);
i++;
setTimeout(typewriter, speed);
}
}
<div class="search-contain">
<button class="search fa fa-search" id="search-btn">button</button>
<input type="text" id="search" placeholder=""></input>
</div>
Now you can add more CSS
or modify the existing one as you want.