views:

15

answers:

2

Hi Everyone!

I'm attempting to create a div tag and then alter it via css, but for some reason its not working here's my code:

$('#draw').click(function(e){
  var divToAdd = "<div id='box' style='display:block;background-color:red;width:100px;height:100px'></div>";
  $("#area").append(divToAdd);
});
$('#left').click(function(e){
  //var leftNow = document.getElementById("box").left + 1;
  alert(document.getElementById("box").left);
  $("#box").css('left',leftNow);
});
$('#right').click(function(e){
  var leftNow = document.getElementById("box").left - 1;
  $("#box").css("left","90");
});

So for some reason the value of document.getElementById("box").left is undefined. I've been trying to figure this out for a while, i've probably got something wrong in my syntax perhaps? Any help would be appreciated, thanks alot! Thank you Nick Craver.

+4  A: 

You would need .style.left, or $("#box").css('left'); in this case.

But...there's an easier way, like this:

$("#box").css("left","-=1");

You can just make it relative this way, same for +=, keep it simple :)

Nick Craver
Thank you sir, this is indeed the case, man i spent ages on this thanks a lot! Ill mark this correct asap.
Pete Herbert Penito
@Pete - Welcome! :)
Nick Craver
oh Nick, you are always faster than me.
Danny Chen
A: 

Here I have two suggestions:

(1)Use jQuery object instead of object itself

var divToAdd = $("<div id='box' style='display:block;background-color:red;width:100px;height:100px'></div>");

Actually the expression above is not so good either, to make it more 'jQuery":

var divToAdd = $('<div></div>').css('background-color','red').css....

(2) Keep using jQuery if you involved it

$('#box').css('left') instead of document.getElemengById(...)
Danny Chen