I have written some jQuery (with much help from Stack Overflow!) that slides open a panel on click, and changes the toggles of the clickable bit from 'Show All' to 'Hide All'.
It works, but I'm trying to figure out what would be the most efficient way to do it, as it seems kind of long to me, and some HTML is repeated.
I've tried using variables and assigning the HTML to be repeated, but it doesn't work and I can't figure out where the problem in my logic is!
This is the working version and a working fiddle here :
$(function () {
//Hide panel with jQuery and create toggle button so subjects will just show up if there's no javascript
$("#panelSub").hide();
$('#toggleSubjects').html('<h4 class="subjectOpen"><i class="fa fa-arrow-circle-down"></i>Show All Subjects<i class="fa fa-arrow-circle-down"></i></h4>');
//Toggle extra subject panel
$("#toggleSubjects").click(function () {
$("#panelSub").slideToggle();
//Change toggle text for show / hide
if ($.trim($('.subjectOpen').text()) === 'Show All Subjects') {
$(this).html('<h4 class="subjectOpen"><i class="fa fa-arrow-circle-up"></i>Hide All Subjects<i class="fa fa-arrow-circle-up"></i></h4>');
} else {
$(this).html('<h4 class="subjectOpen"><i class="fa fa-arrow-circle-down"></i>Show All Subjects<i class="fa fa-arrow-circle-down"></i></h4>');
}
});
return false;
});
And this is the 'more efficient' non-working version I've been trying, apologies in advance for how bad it is :/
var pOpen = '<h5 class="subjectOpen"><i class="fa fa-arrow-circle-down"></i>Show All Subjects <i class="fa fa-arrow-circle-down"></i></h5>';
var pClose = '<h5 class="subjectOpen"><i class="fa fa-arrow-circle-down"></i>Show All Subjects <i class="fa fa-arrow-circle-down"></i></h5>';
var p = $('#toggleSubjects').html();
$(function() {
//Hide panel with jQuery and create toggle button so subjects will just show if there's no javascript
$("#panelSub").hide();
var p = pOpen.html().appendTo('panelSub');
//Toggle subject panel
$("#toggleSubjects").click(function(){
$("#panelSub").slideToggle("slow");
//Change toggle text for show / hide
if ($.trim($('.subjectOpen').text()) === 'Show All Subjects') {
$(this).html() === pClose.html();
} else {
$(this).html()=== pOpen.html();
}
});
return false;
});