JavaScript div creation
Need a small hand here im trying to combine two functions to create a program that takes text from a text area and inserts it into a div (managed that with the first code) the second peace of code im trying to create a div each time, what id like to do is everytime some one writes in the textarea and "posts" the message it will create a new div (rather than the first code which overwrites if anything new is posted).
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('#test').html(x);
return false;
});
});
second:
function creatediv(id, html, width, height, left, top) {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
if (width) {
newdiv.style.width = 300;
}
if (height) {
newdiv.style.height = 300;
}
if ((left || top) || (left && top)) {
newdiv.style.position = "absolute";
if (left) {
newdiv.style.left = left;
}
if (top) {
newdiv.style.top = top;
}
}
newdiv.style.background = "#00C";
newdiv.style.border = "4px solid #000";
if (html) {
newdiv.innerHTML = html;
} else {
newdiv.innerHTML = "nothing";
}
document.body.appendChild(newdiv);
}
Being careful tho as I hav开发者_高级运维e divs set by css for my master page in asp, dont want to overwrite them. Its important I dont add them to the same div aswell as I will be adding more code later that will contain a button inside the created div to add comments to that div only.
Thanks to any and all that can help!
Yeah, don't bother re-inventing the wheel. Get a library like jQuery and learn it. Faster, easier.
http://jquery.com/
But since jquery is one of your tags, I take it that you are using it?
In that case, just use append:
http://api.jquery.com/append/
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('#test').append(x);
return false;
});
});
Basically it would be:
$(function () {
$('button').click(function () {
var x = $('textarea').val();
creatediv(..., x, ...);
return false;
});
});
However you'd need to provide the other parameters (id, width, height, left, top) of your function somehow. From your description I can't say what you would want to use there.
BTW, your creatediv
has errors. The style properties width
, height
(and left
and top
) require units, so you have to use (for example):
newdiv.style.width = "300px";
See the DEMO I think that's what u wanted to do.
精彩评论