David G
David G

Reputation: 96835

How to resize a div based on mouse location?

I'm trying to make a div that expands left, right, up, and down depending on where the mouse is. But when I move the mouse, the div just pops up and doesn't do anything. What is wrong in what I'm doing?

(function() {
    document.onmousemove = function(e) {
        draw(e);
    };

    function draw(e) {
        var method = [
            e.pageX ? e.pageX : e.clientX,
            e.pageY ? e.pageY : e.clientY
        ];
        var X = method[0],
            Y = method[1];
        var html = '<div class="box" style="padding-top:' + Y + ';padding-bottom:' + Y + ';padding-left:' + X + ';padding-right:' + X + '"></div>'
            ;
        document.body.innerHTML = html;
    }
})();​

Upvotes: 0

Views: 221

Answers (4)

Kunal Vashist
Kunal Vashist

Reputation: 2471

You were missing px suffix with the x and Y

(function() {
        document.onmousemove = function(e) {
            draw(e);
        };

        function draw(e) {
            var method = [
                e.pageX ? e.pageX : e.clientX,
                e.pageY ? e.pageY : e.clientY
            ];
            var X = method[0],
                Y = method[1];
            var html = '<div class="box" style="padding-top:' + Y +"px" + ';padding-bottom:' + Y +"px" + ';padding-left:' + X +"px" + ';padding-right:' + X  +"px" + '"></div>'
                ;
            document.body.innerHTML = html;
        }
    })();​

Upvotes: 0

lamplightdev
lamplightdev

Reputation: 2081

CSS length attributes (padding, margin, height, width etc.) require units - px, em etc. So just having:

padding-top:10

is invalid. Instead you need to add units:

padding-top:10px

So in your case the line setting the html should read:

var html = '<div class="box" style="padding-top:' + Y + 'px;padding-bottom:' + Y + 'px;padding-left:' + X + 'px;padding-right:' + X + 'px"></div>';

Upvotes: 0

ComFreek
ComFreek

Reputation: 29434

You forgot the unit px:

(function() {
    document.onmousemove = function(e) {
        draw(e);
    };

    function draw(e) {
        var method = [
            e.pageX ? e.pageX : e.clientX,
            e.pageY ? e.pageY : e.clientY
        ];
        var X = method[0],
            Y = method[1];
        var html = '<div class="box" style="background-color:red;padding-top:' + Y + 'px;padding-bottom:' + Y + 'px;padding-left:' + X + 'px;padding-right:' + X + 'px"></div>'
            ;
        document.body.innerHTML = html;
    }
})();​

(I've also added a red background in order to make the DIV visible)

jsFiddle: http://jsfiddle.net/8LUwp/

Upvotes: 2

Quentin
Quentin

Reputation: 944005

X and Y are numbers. CSS lengths require units. Add some px.

Upvotes: 1

Related Questions