I've written a simple accordion using zepto js lib.
Looking for advice on how to improve this better.
HTML
<div class="box">
<span class="learn-more"><a href="#">Learn more</a></span>
<div class="more">
blah<br>
blah<br>
blah<br>
<span class="close"><a href="#">close</a></span>
</div>
</div>
<div class="box">
<span class="learn-more"><a href="#">Learn more</a></span>
<div class="more">
blah<br>
blah<br>
blah<br>
<span class="close"><a href="#">close</a></span>
</div>
</div>
Javascript
$('.more').addClass('hide');
var learnMore = $('.learn-more'),
close = $('.close');
learnMore.click(function() {
$(this).hide().next('div').toggleClass('hide');
});
close.click(function() {
$(this).parent().toggleClass('hide');
$(this).parent().prev().show();
});
Working demo
How can I prevent the page from jumping when I click on the empty anchor tags?
1 Answer 1
There are a couple of inconsistencies which you could tidy up. You're toggling classes to show/hide the div but using show/hide directly on the triggers. You're using chaining in one onClick but not in the other. And you're using the class to reference the accordion contents in one case, but the element name in the other.
$('.more').hide();
var learnMore = $('.learn-more'),
close = $('.close');
learnMore.click(function() {
$(this).hide().next('.more').show();
});
close.click(function() {
$(this).parent().hide().prev('.learn-more').show();
});
Fiddle
is one possible way of making everything consistent, although you may prefer to always toggle classes instead (or to add animations).
$('.box .learn-more a, .box .close a').click(function(e){e.preventDefault();});
\$\endgroup\$