step
step

Reputation: 25

JQuery .center is not a function

I am working on JQuery. I am getting this error. I ma trying to find out the root cause but i am not able to find it. If any one can help me out that would be really great.

JS ERROR:

Uncaught TypeError: $(...).center is not a function
at HTMLDivElement.<anonymous> (myjs:879)
at HTMLDivElement.opt.complete (jquery-1.8.3.js:9154)
at fire (jquery-1.8.3.js:974)
at Object.add [as done] (jquery-1.8.3.js:1020)
at Animation (jquery-1.8.3.js:8719)
at HTMLDivElement.doAnimation (jquery-1.8.3.js:9034)
at Function.dequeue (jquery-1.8.3.js:1895)
at HTMLDivElement.<anonymous> (jquery-1.8.3.js:1938)
at Function.each (jquery-1.8.3.js:611)
at init.each (jquery-1.8.3.js:241)

My Script:

function centerdiv() {
    $('#id').show(0, function () {
         $('#id1').css('z-index','5');
        $('body').css('overflow', 'hidden');
        $('.class').center();
    });
}

All JQuery functions are working and i am not sure why it is stating .center as not a function.

Upvotes: 0

Views: 2166

Answers (2)

Aaron Brock
Aaron Brock

Reputation: 4536

Your error is telling you that there is no $.center(). But, you can make one!

Here's an example by from this answer by Tony L.

jQuery.fn.center = function(parent) {
    if (parent) {
        parent = this.parent();
    } else {
        parent = window;
    }
    this.css({
        "position": "absolute",
        "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
        "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
    });
return this;
}

$("div.target:nth-child(1)").center(true); // Center relitive to parent
$("div.target:nth-child(2)").center(false); // Center relitive to window
div.container{
    width:200px;
    height:200px;
    border:1px solid #555;
    position:relative;
    top:10px;
    left:10px;
}

div.target{
    width:60px;
    height:60px;
    color:white;
    background:rgba(30,30,30,.7);
    border-radius: 10px;
    text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="target">1<br>parent</div>
    <div class="target">2<br>window</div>
</div>

Upvotes: 2

Ringo
Ringo

Reputation: 5483

The error means $.center() is not a jQuery method you can use. Instead of trying to call a method that doesn't exist, you have to change the CSS to center something. For example:

Centering a div vertically & horizontally using jQuery

You can create your own center method, but you cannot just call $.center() because it doesn't exist.

Upvotes: 0

Related Questions