I am trying to use jquery to toggle the display property (on and off) for some classes.
I am trying to swap between an image and the text below, to toggle on click
<div class="fab red off">
<img class="community_service_icon" src="http://placehold.it/50x50">
<div class="community_service_text">
Charity Run<br/>
Charity Sale<br/>
Bake Sale<br/>
Photo Exhibition<br/>
</div>
</div>
Here are my jquery functions:
jQuery(function($) {
$('.fab.red.off').click(function() {
$(this).removeClass( 'off' ).addClass( 'on' );
$(this).children( '.community_service_icon' ).css('display', 'none');
$(this).children( '.community_service_text' ).css('display', 'block');
});
});
jQuery(function($) {
$('.fab.red.on').click(function() {
$(this).removeClass( 'on' );
$(this).addClass( 'off' );
$(this).children( '.community_service_icon' ).css('display', 'block');
$(this).children( '.community_service_text' ).css('display', 'none');
});
});
The first click successfully hides the image and displays the text, it also changes the classes to 'fab red on'. However, when i click on the fab div again, it seems to run the first function with the selector '.fab.red.off' and the other function is not triggered.
Any ideas? and any suggestions to optimize this code is also much appreciated.
Cheers
You could simplify your code using .toggle()
, which will hide the element if it is visible and show if it is not.
jQuery(function($) {
$('.fab.red').click(function() {
$(this).find('.community_service_icon').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="fab red">
<img class="community_service_icon" src="http://placehold.it/50x50">
<div class="community_service_text">
Charity Run
<br/>Charity Sale
<br/>Bake Sale
<br/>Photo Exhibition
<br/>
</div>
</div>