patternjavascriptMinor
Toggling button & content with jQuery
Viewed 0 times
withtogglingjquerybuttoncontent
Problem
This hides
While the below works, I was wondering if there was a more concise way of writing this code.
div.extended then creates a button that toggles its text and div.extended's visibility.While the below works, I was wondering if there was a more concise way of writing this code.
(function() {
var extended = $('.extended').hide();
$('', {
text: 'Read more'
}).appendTo('.intro')
.on('click', function(){
extended.slideToggle();
}).toggle(
function(){
$(this).text('Read Less')
},
function(){
$(this).text('Read More')
});
})()Solution
$(function () {
var extended = $('.extended').hide(),
hidden = true;
$('', {
text: 'Read more'
}).appendTo('.intro').on('click', function () {
extended.slideToggle();
hidden = !hidden;
$(this).text(hidden ? 'Read More' : 'Read Less');
});
});You only need to bind the click event once (toggle is a shortcut for binding to click and attaching two alternating event handlers).
Code Snippets
$(function () {
var extended = $('.extended').hide(),
hidden = true;
$('<button></button>', {
text: 'Read more'
}).appendTo('.intro').on('click', function () {
extended.slideToggle();
hidden = !hidden;
$(this).text(hidden ? 'Read More' : 'Read Less');
});
});Context
StackExchange Code Review Q#11344, answer score: 4
Revisions (0)
No revisions yet.