Reputation: 33
I am fairly new to javascript and I am trying to create an interface where multiple users input a string of text into a form, and after submitting, the text appears randomly on the page along with the previous users input. Is there a way to do this with javascript? I am mostly having issues with finding a way to write text to a specific location on the screen.
Upvotes: 1
Views: 5599
Reputation: 154908
The idea is that you create a new element each time, and set the following CSS on it so as to be able to position it manually:
position: absolute;
left: _px;
top: _px;
where _
can be generated through Math.random()
. This function returns a decimal value between 0 and 1, so stretch and round it appropriately to get random integer pixel coordinates on the screen: http://jsfiddle.net/6eTcD/2/.
document.querySelector("form").addEventListener("submit", function(e) {
e.preventDefault();
var fullWidth = window.innerWidth;
var fullHeight = window.innerHeight;
var text = this.querySelector("input[type='text']").value;
var elem = document.createElement("div");
elem.textContent = text;
elem.style.position = "absolute";
elem.style.left = Math.round(Math.random() * fullWidth) + "px";
elem.style.top = Math.round(Math.random() * fullHeight) + "px";
document.body.appendChild(elem);
});
Upvotes: 1
Reputation: 7347
You can try a div with absoloute positioning like this:
in your html code: my text
In you CSS #mydiv { position:absolute; top:0; right:0; width:200px; }
You can position your div with jquery
$('div.example').css('top', 100);
References:
Upvotes: 0