Reputation: 109
When a user clicks on a <p>
element I want its text to be in a textarea
element. My problem is that the text that appears in the textarea is beneath one blank row and on top of that shifted to the right.
Why is this happening?
I also tried to put the textarea into a div and to fix it with positioning but that didn't work.
I want to achieve it with pure *JavaScript** and if needed CSS.
Here's what I have so far:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="p1">
text text text text text text text text text text text,
text text text text text text text text text text text,
text text text text text text text text text text text,
text text text text text text text text text text text.
</p>
<div id="holder"></div>
<script type="text/javascript">
var text_to_copy = document.getElementById('p1').innerHTML;
var holder = document.getElementById("holder");
var input = document.createElement("textarea");
document.getElementById('p1').onclick = function(){
input.id = "textarea_id";
input.style.display = "block";
input.style.padding = "0px";
input.style.margin = "0px";
//input.style.textAlign = "left"; does not do anything
input.style.width = "562px";
input.value = text_to_copy;
alert(input.value);//just to see if onclick works
holder.appendChild(input);
}
</script>
</body>
</html>
Upvotes: 0
Views: 90
Reputation: 23610
You could replace multiple tabs and whitespaces (which appear due to your formatting) with a single whitespace before setting the value of the textarea, like:
input.value = text_to_copy.replace(/\s{1,}/g, ' ');
Demo
Explanation
What you see is a regular expression pattern. The \s
is a special character that matches a single white space character (including space, tab, form feed and line feed). g
is a flag and stands for global search, meaning the expression will match all occurrences. {1,}
finally means to match the preceding character one or multiple times. It's equivalent to +
.
Upvotes: 1
Reputation: 175
You move the content inside the textarea , the spaces that you have left within the tag . Then I show you an example , that you do not put the first line spacing , or to the left .
var text_to_copy = document.getElementById('p1').innerHTML;
var holder = document.getElementById("holder");
var input = document.createElement("textarea");
document.getElementById('p1').onclick = function(){
input.id = "textarea_id";
input.style.display = "block";
input.style.padding = "0px";
input.style.margin = "0px";
//input.style.textAlign = "left"; does not do anything
input.style.width = "562px";
input.value = text_to_copy;
alert(input.value);//just to see if onclick works
holder.appendChild(input);
}
<html>
<head>
</head>
<body>
<p id="p1">text text text text text text text text text text text,
text text text text text text text text text text text,
text text text text text text text text text text text,
text text text text text text text text text text text.</p>
<div id="holder"></div>
</body>
</html>
Upvotes: 1