Reputation: 219
I have 100 images on a website, and I want to be able to search in the search box the file name of the image. After that for the image to be highlighted when found. Files are named 0-1.png, 0-2.png, etc. So if I type 0-1 to highlight image 0-1.png. Here is what I have so far.
<form action='' method='get'>
<input type="text" name="search" size="3" maxlength="3">
<input type="submit" value="search">
</form>
How do I create a Javascript function to search for image and highlight it?
Also images are stored in path like images/0-1.png
Upvotes: 1
Views: 1436
Reputation: 141829
Something like this may work for you:
<input type="text" id="search" />
<div id="images">
<img src="0-1.png" />
<img src="0-2.png" />
...
</div>
<script>
(function(){
var input = document.getElementById('search');
var images = document.getElementById('images').getElementsByTagName('img');
input.onkeyup = function(){
for(var i = images.length; i--;){
images[i].className =
images[i].src.indexOf(this.value) > 0 ?
'highlight' :
'';
}
};
})();
</script>
With this in your CSS:
img.highlight {
border: 5px solid #F0F;
margin: -5px;
}
Upvotes: 2
Reputation: 1375
Add a id="search" to your input name="search" textbox. Include jquery. Add the following code in your head statement. Drop the search button
<script>
$(function() {
$('#search').keyup(function() {
$('img')
.removeClass('highlight')
.filter('img[src*="'+$(this).val()+'"]')
.addClass('highlight');
});
});
</script>
CSS:
img { border: 3px solid transparent; }
img.highlight { border-color: yellow; }
http://jsfiddle.net/fstreamz/8kCxw/3/
Upvotes: 1