Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Boris Kamp
Boris Kamp
16,660 Points

Javascript function inside conditional statement

Hi all,

I writing Javascript to add stuff to the Wordpress backend on different post types. I'm trying to put all the JS in one file and load it. A snippet of my total file is this function:

//Excerpt Length
    var $exc = $('#excerpt');
    var exc = '#excerpt';
    var exc_length = 0;
    //check if div exists
    if($exc.length > 0 ) {
        function charcount(target, counterdiv){
            exc_length = $(target + ' ' + counterdiv).val().length;
            return exc_length;
        //var exc_length = charcount(exc);
        function exc_appender(){
            return $exc.append('<span id="exc-charcount">' + exc_length + '/500 characters used</span>');
        //keyup function for re-calculation
        $(exc + ' textarea').keyup(function(){

I tried to wrap it in an if statement because the function gives errors on pages where #excerpt is not present.

wrapping everything in a conditional statement still gives me errors tho, how can I fix this?

I know I can load .js files conditionally in my functions.php and fix it that way, but that means I have to write multiple javascript files in order to achieve what I want, and Im wondering if it can be done within one file......