DEV Community

Saugat Rai
Saugat Rai

Posted on

So while learning javascript, I created superhero image filter using tags.

This is the final product that we will create.

At first the html structure will be like:

The main trick here is to add these data- attributes. Here each img tag has a data-tags attribute with multiple value.

This conclude our html part. Next move on to the javascript part.

The magic happens here

The first thing is to make variables to hold the element.

Then loop over each images to store corresponding tags and img element in tagged object variable that we have created above.

The if block checks for tags, loop through those tags and create an object with key of tag name and value of related img element.

Each img corresponds to img tag on html.


The next step is to create buttons. First we will create 'Show All' buttons

The main function of this button is to only show all the images, add active class to current one and remove active class in all other buttons. i.e siblings(). Lastly, the button is append to buttons variable that we created earlier.

One button down more to go.

This will be the last function needed to filter the image.

This function will generate a button with number of related images it holds and filter images when clicked. It iterates through the tagged variable. The tagName is the name of each tags. Thus, the button text will be the name of tag.

On click event first all the images will be hidden, then filtered using filter() function in jQuery which in our case accept the argument tagged[tagName] and finally show those images.
Each button is then append to buttons variable.

And finally the whole function is wrapped in Immediately Invoked Function Expressions (IIFE).

The reason behind to build this was to know the mechanism of how this works. This is my first tutorial blog. Hope this helps.
Kudos :)

Top comments (3)

raisaugat profile image
Saugat Rai

Thank you :)

titungdup profile image

Nice tutorial, Easy to follow. Congratulations on your first blog! Hope to see more :)

raisaugat profile image
Saugat Rai

Thank you. Will be posting more soon. :)