0

I have loaded an external JavaScript file, and placed functions within it, but when running the functions, it says "undefined function", but when I place the functions within the index file, it works perfectly.

To debug this, I wrote alert('entered'); when entering the document, and reading content when running and document is ready. Both are executed.

The error U get with this is:

Uncaught ReferenceError: countdown is not defined
Uncaught ReferenceError: keepalive is not defined

How can I fix this?

Source:

   // JavaScript Document

alert('entered js.js');

$(document).ready(function() {
alert('reading content');
    function countdown() {
        var ele = document.getElementsByClassName('countdown');
        for (var i = 0; i < ele.length; ++i) {
            var v = Math.floor(ele[i].getAttribute('ctime')) - 1;
            if (v < 0) {
                v = 0;
            }
            ele[i].setAttribute('ctime', v);
            if (v > 86399) {
                var sl = v;
                d = parseInt(sl / 86400);
                sl = sl % 86400;
                h = parseInt(sl / 3600);
                sl = sl % 3600;
                m = parseInt(sl / 60);
                s = parseInt(sl % 60);
                var str = d + 'd ' + h + 't ' + m + 'm ' + s + 's';
            } else if (v > 3599) {
                var h = Math.floor(v / 60 / 60);
                var m = Math.floor((v - (h * 3600)) / 60);
                var s = v - (m * 60) - (h * 3600);
                var str = h + 't ' + m + 'm ' + s + 's';
            } else if (v > 59) {
                var m = Math.floor(v / 60);
                var s = v - (m * 60);
                var str = m + 'm ' + s + 's';
            } else if (v > 0) {
                var str = v + 's';
            } else {
                var str = ele[i].getAttribute('ctext') || '0s';
            }
            if (v == 0) {
                var act = ele[i].getAttribute('caction');


                if (act != '') {
                    setTimeout(function() {
                        url(act);
                    }, 1000);
                }
            }
            ele[i].innerHTML = str;
        }
        setTimeout('countdown()', 1000);
    }








    $( ".specialpost tr" ).click(function(e) {

        var form = $(this).parents('form').attr('id');
        var submitformId = $(this).data("submitid");
        console.log(form);
        console.log(submitformId);
        $("#submitvalue").val(submitformId);
        $( "#" + form ).submit();

    });





    (function ($) {
        $.fn.countTo = function (options) {
            options = options || {};

            return $(this).each(function () {
                // set options for current element
                var settings = $.extend({}, $.fn.countTo.defaults, {
                    from:            $(this).data('from'),
                    to:              $(this).data('to'),
                    speed:           $(this).data('speed'),
                    refreshInterval: $(this).data('refresh-interval'),
                    decimals:        $(this).data('decimals')
                }, options);

                // how many times to update the value, and how much to increment the value on each update
                var loops = Math.ceil(settings.speed / settings.refreshInterval),
                    increment = (settings.to - settings.from) / loops;

                // references & variables that will change with each update
                var self = this,
                    $self = $(this),
                    loopCount = 0,
                    value = settings.from,
                    data = $self.data('countTo') || {};

                $self.data('countTo', data);

                // if an existing interval can be found, clear it first
                if (data.interval) {
                    clearInterval(data.interval);
                }
                data.interval = setInterval(updateTimer, settings.refreshInterval);

                // initialize the element with the starting value
                render(value);

                function updateTimer() {
                    value += increment;
                    loopCount++;

                    render(value);

                    if (typeof(settings.onUpdate) == 'function') {
                        settings.onUpdate.call(self, value);
                    }

                    if (loopCount >= loops) {
                        // remove the interval
                        $self.removeData('countTo');
                        clearInterval(data.interval);
                        value = settings.to;

                        if (typeof(settings.onComplete) == 'function') {
                            settings.onComplete.call(self, value);
                        }
                    }
                }

                function render(value) {
                    var formattedValue = settings.formatter.call(self, value, settings);
                    $self.text(formattedValue);
                }
            });
        };

        $.fn.countTo.defaults = {
            from: 0,               // the number the element should start at
            to: 0,                 // the number the element should end at
            speed: 1000,           // how long it should take to count between the target numbers
            refreshInterval: 100,  // how often the element should be updated
            decimals: 0,           // the number of decimal places to show
            formatter: formatter,  // handler for formatting the value before rendering
            onUpdate: null,        // callback method for every time the element is updated
            onComplete: null       // callback method for when the element finishes updating
        };

        function formatter(value, settings) {
            return value.toFixed(settings.decimals);
        }
    }(jQuery));






function keepalive() {
    $.ajax({
        url : "http://www.smackface.net/check_user",
        type : "POST",
        dataType : 'json',
        data : {
            method : 'checkAlerts'
        },
        success : function(data, textStatus, XMLHttpRequest) {
            var response = data;


            if (!(response.login)) {
                alert('You are now logging out');
            } else {



            if (response.messages > 0) {

                $('#message_count').show().text(response.messages);
                if ($('#message_count').text() != response.messages) {
                    $("#playsoundappend").html("<audio id=\"playsound\"><source src=\"http://soundbible.com/grab.php?id=1645&type=mp3\" type=\"audio/mpeg\"><source src=\"http://soundbible.com/grab.php?id=1645&type=mp3\" type=\"audio/mpeg\"></audio>");

                    document.getElementById('playsound').play();

                    $('title').text(response.notifications + " messages");
                }


            }
            else {
                $('#message_count').hide();


            }


            if (response.notifications > 0) {

                $('#notification_count').show().text(response.notifications);
                if ($('#notification_count').text() != response.notifications) {
                    $("#playsoundappend").html("<audio id=\"playsound\"><source src=\"http://soundbible.com/grab.php?id=1645&type=mp3\" type=\"audio/mpeg\"><source src=\"http://soundbible.com/grab.php?id=1645&type=mp3\" type=\"audio/mpeg\"></audio>");

                    document.getElementById('playsound').play();

                    $('title').text(response.notifications + " notifications");
                }


            }
            else {
                $('#notification_count').hide();


            }
            }


        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {

            console.log(XMLHttpRequest.responseText);

        }

    });
    setTimeout('keepalive()', 10000);
}


$("#notificationLink").click(function()
{
    $("#notificationContainer").fadeToggle(300);

    $("#notification_count").fadeOut("slow");



    $.ajax({
        url : "http://www.smackface.net/check_user",
        type : "POST",
        dataType : 'json',
        data : {
            method : 'loadNotifications'
        },
        success : function(data, textStatus, XMLHttpRequest) {

            var tpl = $("#notes").html();
            var notification = Handlebars.compile(tpl);

            $("#notificationsBody").html('');
            $("#notificationsBody").append(notification(data));







        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {

            console.log(XMLHttpRequest.responseText);

        }

    });




    return false;
});

$(document).click(function()
{
    $("#notification_count").hide();
});

$("#notification_count").click(function()
{
    return false;
});


    keepalive();
    countdown();


});
2
  • move countdown() outside the document ready method Commented Mar 26, 2015 at 2:19
  • @HiteshSiddhapura tried that too, that dosent work. Commented Mar 26, 2015 at 2:37

1 Answer 1

1

you can pass the function itself to setTimeout:

setTimeout(countdown, 1000);
setTimeout(keepAlive, 1000);

The way you wrote it, it will have to be 'eval'ed out of scope of $(document).ready(... . When you pass the function itself as the first argument, it is in scope.

Sign up to request clarification or add additional context in comments.

3 Comments

Works. Will accept your answer within 8 minutes. Could you tell me more about this, and the evaled out of scope? Because i do not quite understand how that works.
when you pass a string to setTimeout, an event is scheduled at whatever time you specified. When eval is called the window is your scope (not within your jquery function) Any functions you have declared within your jquery block are not available outside the jquery function, and therefore not available at the window scope. By passing the actual function to the setTimeout, the window doesn't have to eval, and the function is successfully called.
There is a lot of code there to look at... Is there another problem you're asking about?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.