2

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.

0

2 Answers 2

5

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir, this is indeed the case, man i spent ages on this thanks a lot! Ill mark this correct asap.
2

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(...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.