2
\$\begingroup\$

I have written some jQuery 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.

This is the working version and a working fiddle here:

$(function() {
    //Hide panel with jQuery and create toggle button so subjects will just show if there's no javascript
$("#panelSub").hide();
$('#toggleSubjects').html('<h5 class="subjectOpen"><i class="fa fa-arrow-circle-down"></i>Show All Subjects <i class="fa fa-arrow-circle-down"></i></h5>');
    //Toggle extra subject panel
    $("#toggleSubjects").click(function(){
        $("#panelSub").slideToggle("slow");
        //Change toggle text for show / hide
            if ($.trim($('.subjectOpen').text()) === 'Show All Subjects') {
            $(this).html('<h5 class="subjectOpen"><i class="fa fa-arrow-circle-up"></i>Hide All Subjects <i class="fa fa-arrow-circle-up"></i></h5>');
            } else {
            $(this).html('<h5 class="subjectOpen"><i class="fa fa-arrow-circle-down"></i>Show All Subjects <i class="fa fa-arrow-circle-down"></i></h5>');      
                }
            });
            return false;
}); 
\$\endgroup\$
1
  • \$\begingroup\$ Hi emerfan, and welcome to Code Review! While we can certainly giv eyou tips on your working code. Any code that is not currently working does not fall within our question guidelines. \$\endgroup\$ Commented Apr 22, 2015 at 13:16

1 Answer 1

2
\$\begingroup\$

Please check out this updated jsFiddle: https://jsfiddle.net/b4mp044z/5/

I've changed your JS code into :

$(document).ready(function () {    
    $("#panelSub").hide();

    $("#toggleSubjects").click(function () {
        $("#panelSub").slideToggle("slow");                
        $(this).find('i').toggleClass('fa-arrow-circle-down fa-arrow-circle-up')
    });
    return false;
});

and updated your HTML and CSS to hold all your structure and content. It's a good practice to keep things separated (HTML, CSS and JS)

\$\endgroup\$
1
  • \$\begingroup\$ Hey that's great thanks! except for one thing! If there is no JS, the 'Show All Subjects' 'Hide All Subject's bar shoudn't appear, so it needs to be created with the function :) \$\endgroup\$
    – hereiam
    Commented Apr 22, 2015 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.