David
David

Reputation: 1

Jquery element width

I've made a function in order to center-align a submit button in forms :

function btnCentrage(element, parent){
    var widthForm = $(parent).innerWidth();
    var widthBtn = $(element).outerWidth();
    var placement = (widthForm - widthBtn) / 2;
    console.log(element + '/' + parent + '/' + widthForm + '/' + widthBtn + '/' + placement);
    $(element).css('margin', '0 '+ placement + 'px');
}
    btnCentrage('#connectForm .btn_small', '.connect_bottom');

When I call this function (after DOM loading), it doesn't have any element width or parent width.

Upvotes: 0

Views: 1355

Answers (3)

kasdega
kasdega

Reputation: 18786

Your code appears to work so the answer is that the elements are either not being selected correctly (as Ianus says) or your elements are not visible as Shankar says.

And as was also pointed out you can easily use CSS to do this.

Your code: http://jsfiddle.net/kasdega/QbvxA/

One possible CSS Version: http://jsfiddle.net/kasdega/QbvxA/1/

Upvotes: 0

Jules
Jules

Reputation: 7223

In JQuery you just use width().

As explained here, you can just do:

var widthBtn = $(element).width();

Upvotes: 1

Ianus Chiaroscuro
Ianus Chiaroscuro

Reputation: 229

The most obvious reason that would be the case is that it's not finding the element or parent. Try adding $(parent).length and $(element).length to your console.log debug dump so you see whether it's actually locating your DOM nodes.

Upvotes: 0

Related Questions