Reputation: 1
At the moment I have a search bar which is supposed to, when text is inputed into it, filter down a number of images. At the moment I have this:
searchbar:
<input type="text" placeholder="Search for Products..." id="top-bar_search"></input>
Images:
<div id="table">
<img src="img/Shoes/Mens_Casual1.jpg"id="a"/>
<img src="img/Shoes/Mens_Sport2.jpg"id="b"/>
</div>
And the Javascript (jQuery):
var $rows = $('#table img #');
$('#top-bar_search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
How do I make it so this works properly and the code shows or hides images based on their id, thanks.
Upvotes: 0
Views: 662
Reputation: 3838
I've prepared an example for you: http://jsfiddle.net/jarrodek/QPSHq/1/
Later you can replaces spans with images. I replaced it to explain the rule.
There's two functions: hideCss and hideManually. Both do different things but are based on the same rule.
First I've added attributes to span elements (images in your case):
<span data-producst="mens casual">#1 mens casual</span>
The app will search over this attributes for keywords.
Next you need to match user's input with those keywords. We can use CSS3 selectors for that:
For css based function:
var cssCode = '#table span[data-producst]{display:none;} #table span[data-producst*="'+query+'"]{display: inline-block;}
Then append it to the document as a css rule. It is working out of the box.
For javascript based function (if you need it for some reason):
var elements = document.querySelectorAll('#table span[data-producst*="'+query+'"]');
And then iterate over elements and show them (you need to hide all first).
Check jsFiddle code above for full example and my comments explaining how it works.
If you can base on CSS rules only it is better for performance. CSS is better performing than javascript. So if it fit your needs you should use it. However you may want to add some extra code you can do it using second function: hideManually. Or combine both methods.
Upvotes: 2