I have put an image into my search bar as a placeholder. I am hiding it with input:focus, but that will cause it to reappear when I unclick it. Is there a way to only hide it, and keep it hidden when there is an input in the search bar?
The image reappears on unfocus and load of new page.
function myFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("mySearch");
filter = input.value.toUpperCase();
ul = document.getElementById("myMenu");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
input {
border: 0px;
outline: none;
border-bottom:3px solid #00A7E0;
width: 90%;
background-image: url("../images/searchImage.png");
background-repeat: no-repeat;
background-size: 25%;
padding: 10px;
}
input:focus {
background-image: none;
}
<input type="text" id="mySearch" onkeyup="myFunction()" onfocus="removeAttr()" title="Type in a category">
2
Answers
You can write a function that adds a specific className to myFunction in onkeyup if there is no input value. And in the css part, you can make the background-image disappear when there is a specific className
Example
HTML
CSS
Javascript
I hope this helps!
The best approach here; as has been suggested in the comments, is to do this using javascript. It is a good idea to add the image to the search bar using a css class:
Then adding that class to the input field in the HTML file:
Finally, adding that removeImg function definition that handles removing the ‘with-image’ class from the input tag if it is not empty, otherwise it adds it back: