Thomas Ayoub
Thomas Ayoub

Reputation: 29461

change margin-left with JS

I want a dynamical margin-left on a given div.

I tried this code :

window.onload = function()
{
    var pageWidth = window.innerWidth; 
    var size = (pageWidth - 200 ) / 2;
    $('#search').css('margin-Left', size));
    alert(size);
 };

which doesn't work (the alert is here just for test purpose), the problem is coming from the ligne $('#search').css('margin-Left', size)); but I can't find out where...

I've tried with a lowercase l on margin-left and didn't work.

Upvotes: 6

Views: 19479

Answers (4)

Giovanni Silveira
Giovanni Silveira

Reputation: 1281

You need to specify the type of unit you want to use.

$('#search').css('margin-left', size + 'px');

Upvotes: 1

Harsha Venkataramu
Harsha Venkataramu

Reputation: 2914

JAVASCRIPT

$(document).ready(function(e){
    alert('test');
    var pageWidth = parseInt($(window).innerWidth());
    alert(pageWidth);
    var size = (pageWidth - 200 ) / 2;
    $('#search').css('margin-left', size);
    alert(size);
})

HTML

<div id = 'search'></div>

CSS

#search
{
    height:100px;
    width:100px;
    background-color:#F00;
}

FIDDLE LINK

Upvotes: 0

Arthur Weborg
Arthur Weborg

Reputation: 8590

Would the following work for you?

document.getElementById("search").style.marginLeft = size + "px";

Upvotes: 8

Ryan Anderson
Ryan Anderson

Reputation: 154

Try using marginLeft, without the hypen.

jQuery.css() documentation: http://api.jquery.com/css/

Upvotes: 0

Related Questions