Search code examples
javascriptjqueryfunctionruntime-errorobject-expected

Javascript: calling function inside another function not working?


So inside my <script> tags, I have these functions.

$.fn.getRandom = function(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

function placeRandom() {
    alert(getRandom(1,7));
}

and I call the placeRandom() function like so

$(document).ready(function() {
    placeRandom();
});

when I do this, it gives me an

Object expected

error and refers to the line where I wrote

alert(getRandom(1.7));

Now, my main question is if there is anything wrong with the code which I am showing you, or does it look correct? Because if it looks correct then I think i'm going to have to run through the rest of my entire code and look for maybe a open bracket which isn't closed because that might be the problem. So yea, is there any problem with my placeRandom() or getRandom() function or is the error occuring because of another reason other than these functions?


Solution

  • The problem is were you are defining the getRandom function. You are putting it in the jQuery.fn namespace. If you organize your code like the following it should work much better.

    var getRandom = function(min, max) {
        return min + Math.floor(Math.random() * (max - min + 1));
    }
    
    var placeRandom = function() {
        alert(getRandom(1,7));
    }
    
    $(document).ready(function() {
        placeRandom();
    });
    

    Additional Info: jQuery.fn is actually a prototype but is commonly referred to as a namespace in this specific context.