Reputation: 423
I have a json file that every object has 3 keys and values. Description, poster image and genre. Each object is for movies. I succeeded to append poster images and descriptions. But now I want to hide them all and then show the ones that has particular "genre" values when I click a link. I did the hiding stuff. When I click "drama" link, jquery hides all movie posters and descriptions. I want to add the code that can show again the ones with particular "genre" values to it. How can I do it? The code I wrote so far is below. First "drama" is id of the link, second is the value of "genre" key. Each "Box" includes a movies poster and description.
$("#drama").click(function() {
$(".box").hide();
if (data.movies.genre === "drama") {
$(".box").show();
};
});
Upvotes: 0
Views: 88
Reputation: 171690
You can add a class for genre on the elements. Elements can have multiple classes
<div class="box drama">
Then filter that class to show
$("#drama").click(function() {
$(".box").hide().filter('.'+data.movies.genre).show();
});
Upvotes: 0
Reputation: 598
You could use data attributes to do this. So, when you're building the elements, add data-genre attribute. JQuery can select on these attributes and you can hide/show a group of them pretty easily.
Also, to improve quality, you could use the same mechanism on the button/link to show/hide a genre.
In html:
<div class="box" data-genre="drama">DRAMA BOX</div>
<div class="box" data-genre="comedy">COMEDY BOX</div>
<div class="box" data-genre="drama">DRAMA BOX 2</div>
<div class="box" data-genre="romance">DRAMA BOX 2</div>
<button class="filter-button" data-genre="drama">Drama</button>
<button class="filter-button" data-genre="comedy">Comedy</button>
In js:
$(".filter-button").click(function() {
$(".box").hide();
$(".box[data-genre=" + $(this).data('genre') + "]").show();
});
http://jsfiddle.net/ukf3dzy2/1/
Upvotes: 1
Reputation: 4185
You could name each genre box element with its own id and then use a generic method to handle the change.
function showHide(element) {
if(element.id == "drama") {
$("#dramabox").show();
$("#actionbox").hide();
} elseif (element.id == "action") {
$("#actionbox").show();
$("#dramabox").hide();
}
}
then use it in click event call
$("#drama").click(function() {
showHide(this);
});
$("#action").click(function() {
showHide(this);
});
Upvotes: 0