Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialLuka Dadiani
15,397 PointsTrying to create a simple image gallery what am I doing wrong here?
So I'm trying to create a simple image gallery using jQuery but something is not working. What am I doing wrong here?
You can see the pen: http://codepen.io/LukaDadiani/pen/RpvxZV
2 Answers
Luka Dadiani
15,397 Points@runenielsen Thanks for the answer, i some to have got it working but how would one re-factor this to be less repetitive?
Rune Andreas Nielsen
5,354 PointsA way to simplify the solution would be to abstract the logic of adding and removing CSS classes away to a separate function, that all of the buttons can use.
$(document).ready(() => {
$('.btn1').click(() => {
toggleImage('.image_1', '.image_2, .image_3');
});
$('.btn2').click(() => {
toggleImage('.image_2', '.image_1, .image_3');
});
$('.btn3').click(() => {
toggleImage('.image_3', '.image_1, .image_2');
});
function toggleImage(removedClass, addedClass) {
$(removedClass).removeClass("hide");
$(addedClass).addClass("hide");
}
});
I added arrow functions, but you don't have to do that, if you're not familiar with them yet. Here is the solution without:
$(document).ready(function () {
$('.btn1').click(function () {
toggleImage('.image_1', '.image_2, .image_3');
});
$('.btn2').click(function () {
toggleImage('.image_2', '.image_1, .image_3');
});
$('.btn3').click(function () {
toggleImage('.image_3', '.image_1, .image_2');
});
function toggleImage(removedClass, addedClass) {
$(removedClass).removeClass("hide");
$(addedClass).addClass("hide");
}
});
Rune Andreas Nielsen
5,354 PointsRune Andreas Nielsen
5,354 PointsHi, Luka. What is the issue on the application?