I've just implemented a simple expand/collapse system on part of our website. I tried a couple of existing solutions but it just felt like too much effort to adapt the site to fit to it, so I wrote my own that fitted.
The code is as below:
function hide(boxtohide, boxtomodify, expandbox) {
$('#' + boxtohide).hide(300);
$('#' + boxtomodify).css('background-image', 'url("images/new/date.png")');
$('#' + boxtomodify).css('height', '69px');
$('#' + expandbox).show(300);
}
function show(boxtohide, boxtomodify, expandbox, origheight, origurl) {
$('#' + expandbox).hide(300);
$('#' + boxtomodify).css('height', origheight);
$('#' + boxtomodify).css('background-image', 'url("'+origurl+'")');
$('#' + boxtohide).show(300);
}
The logic behind is this:
and in reverse for expanding again.
To me the code just feels a bit clunky, I'm not a javascript whiz so perhaps a little out of depth here and any suggestions are welcomed!
Dave
The only obvious change I'd suggest is the $('#' + boxtomodify')
lines, which can be compressed to:
function hide(boxtohide, boxtomodify, expandbox) {
$('#' + boxtohide).hide(300);
$('#' + boxtomodify).css({
'background-image' : 'url("images/new/date.png")'),
'height' : '69px' });
$('#' + expandbox).show(300);
}
function show(boxtohide, boxtomodify, expandbox, origheight, origurl) {
$('#' + expandbox).hide(300);
$('#' + boxtomodify).css({
'height' : origheight
'background-image' : 'url("'+origurl+'")' });
$('#' + boxtohide).show(300);
}
You could speed up the code simply getting each element first in JS, and chain those CSS modifications, as follows:
function hide(boxtohide, boxtomodify, expandbox) {
var hideElem = document.getElementById(boxtohide),
modElem = document.getElementById(boxtomodify),
expandElem = document.getElementById(expandbox),
cssObj = { 'background-image' : 'url("images/new/date.png")',
'height' : '69px' };
$(hideElem).hide(300);
$(modElem).css(cssObj);
$(expandElem).show(300);
}
I bet you're approaching this way too complicated, with jQuery you can do such things with a minimum of code, for example:
$('.toggle').on('click', 'h3', function() {
var $content = $(this).next('.content');
$content.slideToggle('fast');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.