Scenario: I have created a simple Show/Hide function that allows the user to click on an IMG and display the subsequent content.
Expected Behavior: When the user clicks on an IMG, .service-img
, I would like the selected IMG content, .service-content
, to .addClass('fadeIn');
while .removeClass('fadeIn');
from the previously selected/visible content.
Issue: Although the conditional is successful at .addClass('fadeIn');
it fails at .removeClass('fadeIn');
It seems to add the class to all .service-content
when the .service-img
is clicked.
My Assumption: Although I am asking if ($('.service-content').is(':visible')) .addClass etc...
I can never really remove the class because technically .service-content
is always visible when .service-img
is clicked.
Question: How can I properly write the conditional to check if the Current selected element .is(':visible')
then execute function, regardless if all content elements share the same class name.
A few, semi-successful attempts
// Function Attempt 1 shows .service-content but adds .fadeIn
// to .service-img so service content never Fades Into view
$('.service-content').hide();
$('.service-content:first-child').show();
$('.service-img').click(function() {
$('.service-content').hide();
$('.service-content').eq($(this).index()).show();
if ($('.service-content').is(':visible')) {
$(this).addClass('fadeIn')
} else {
$(this).removeClass('fadeIn');
}
});
// Function Attempt 2
$('.service-content').hide();
$('.service-content:first-child').show();
$('.service-img').click(function() {
$('.service-content').hide();
$('.service-content').eq($(this).index()).show();
if ($('.service-content').is(':visible')) {
$('.service-content').addClass('fadeIn')
} else {
$('.service-content').removeClass('fadeIn');
}
});
// Function Attempt 3
$('.service-content').hide();
$('.service-content:first-child').show();
$('.service-img').click(function() {
$('.service-content').hide();
$('.service-content').eq($(this).index()).show();
if ($('.service-content').eq($(this).index()).is(':visible')) {
$('.service-content').eq($(this).index()).addClass('fadeIn')
} else {
$('.service-content').eq($(this).index()).removeClass('fadeIn');
}
});
Here is the complete prototype: JS Fiddle
You don't really need to check if the element is visible. I guess that this would do the trick.
https://jsfiddle.net/3fbzrto0/30/
$('.service-img').on('click', function(){
var index = $(this).index();
var content = $('.service-content').eq(index);
//hide all visible elements
$('.service-content').hide();
$('.service-content').removeClass('fadeIn');
content.show();
content.addClass('fadeIn');
});