I have a textarea that has the id = display
javascript:
<script>
function drag(event) {
event.dataTransfer.setData("text", this.event.target.src);
}
function drop(event) {
event.preventDefault();
let data = event.dataTransfer.files;
for (file of data) {
var l = document.getElementById('display').selectionStart;
var text = document.getElementById("display").value;
sub1 = text.substring(l,0);
var len = text.length;
var l2 = sub1.length;
sub2 = text.substring(len,l2);
var test = sub1 + file.name + sub2;
var end = document.getElementById("display").textContent = test;
alert(end);
}
}
function allow(event) {
event.preventDefault();
}
</script>
I type in some text and want to put the dragged file in between the text. When i run this code, the alert shows the correct content, but the DOM never updates.
This only occurs when i input text in the area myself. For example if text is already in the field and i drag and drop the DOM wont update even though the alert shows the correct content.
I have spent countless hours trying to debug this but cant seem to find a solution.
The demo below you will see if you type in the textarea it doesnt work with the drag and drop. But if you dont press any keys and just keep on dragging images it will work
Demo here
Thanks.
This line:
var end = document.getElementById("display").textContent = test;
Should be:
var end = document.getElementById("display").value = test;
.textContent is replaced with .value
Related
Working on a JavaScript program, and the first thing that happens when run is asking the user whether they want to enter something using prompt()s, or using a textarea. The textarea option comes with a clickable button element to press once the user has entered everything they want into the textarea.
If this option is chosen, I want the rest of my program to not run until this button is clicked, and the user is confirming that they are finished with their input. Currently I have the button code within the selection part (where the user has chosen to use a textarea), as below:
if (trimmedResponse == 'manual') {
... (irrelevant code)
} else { //if paste is chosen
var createArray = function(howMany){
var pasteInput = document.createElement("TEXTAREA");
var makingArray = [];
document.body.appendChild(pasteInput);
pasteInput.rows = howMany;
let done = document.createElement("button");
done.innerHTML = 'Enter terms';
done.onclick = function(){
for (var j = 0; j < howMany; j++){
makingArray[j] = String((pasteInput.value).replace(/ /g,'').split('-')).split('\n');
}
pasteInput.style.display = 'none';
done.style.display = 'none';
}
document.body.appendChild(done);
return makingArray;
}
termArray = window.createArray(numOfTerms); //getting a variable holding the array from the prior function, to access later
}
The rest of the script.js file is made up of the regular subroutines - preload, setup, draw, and some initialisation and other small methods in the open scope before preload(), as below in a greatly reduced format:
let BG;
let translateEdit = document.createElement("button");
translateEdit.innerHTML = "Edit a translation";
translateEdit.style.position = 'absolute';
translateEdit.style.left = '50px';
translateEdit.style.top = '130px';
let list = "";
translateEdit.onclick = function () {
this.blur();
do {
replaceChoice = prompt("Which translation do you want to edit? (1-"+numOfTerms+") \n"+list+" \nOr enter any letter to leave this screen.");
} while (replaceChoice < 1 || replaceChoice > termArray.length)
termArray[replaceChoice-1][1] = prompt("What is the new translation for the term "+termArray[replaceChoice-1][0]+"?");
list = "";
for (let i = 0; i < numOfTerms ; i++){
list += ((i+1)+". ["+termArray[i][0] + "] - [" + termArray[i][1] + "]\n") //adds each term and translation in a user-friendly / clear display to the list variable for later display
}
alert("The term list currently looks as follows: \n"+list);
};
document.body.appendChild(translateEdit);
let temp1;
let temp2;
let temp3;
var performanceDisplay = "";
function preload() { //function loading image from file into variable
Helvetica = loadFont('Helvetica-Bold.ttf');
BG = loadImage('images/background.png');
}
function setup() { //function to create display/background using image file and dimensions and instantiate objects (character,terms,counters) as well as slider and icon to be displayed for it
alert("Below are the terms you have entered: \n" + list + "If any of the above are incorrect, use the edit buttons on the next screen to adjust terms or translations.");
speakericon = loadImage('images/speaker.png');
createCanvas(width, height);
... (further code in setup())
}
function draw() { //make background + objects visible on screen, allow them to act as they must, creating new terms when necessary, calling functions in class files such as player movement (calls all functions in classes throughout function) - all run every tick
image(BG, 0, 0, width, height); //set the display to the background image from BG variable in preload()
... (further code in draw())
}
In essence, I need to stop everything else from running until the button 'done' is clicked, and would appreciate any help with anything to achieve this.
I have successfully created a button which adds text to the webpage however I do not know a viable way to remove text once this has been created. The js code I have is:
var addButtons = document.querySelectorAll('.add button');
function addText () {
var self = this;
var weekParent = self.parentNode.parentNode;
var textarea = self.parentNode.querySelector('textarea');
var value = textarea.value;
var item = document.createElement("p");
var text = document.createTextNode(value);
item.appendChild(text)
weekParent.appendChild(item);
}
function removeText() {
//document.getElementbyId(-).removeChild(-);
}
for (i = 0; i < addButtons.length; i++) {
var self = addButtons[i];
self.addEventListener("click", addText);
}
I have viewed various sources of help online including from this site however I simply cannot get any to work correctly. Thank you in advance.
Sure, it should be easy to locate the added <p> tag relative to the remove button that gets clicked.
function removeText() {
var weekParent = this.parentNode.parentNode;
var item = weekParent.querySelector("p");
weekParent.removeChild(item);
}
If there is more than 1 <p> tag inside the weekParent you will need a more specific querySelector.
My script highlights the keywords but whenever it does, it messes with the string and does random things with the text like reverse it and mix it up.I was wondering if someone could tell me how to unreverse this text or move the cursor to the end of the contenteditable div or at most just fix it for me. I don't want any external libraries just javascript and jquery.
jsfiddle
JS Code:
function UnColor() {
var elem = document.getElementById("editor");
var text = elem.textContent;
elem.innerHTML = text;
}
function Color() {
UnColor();
var elem = document.getElementById("editor");
var code = elem.innerHTML;
code = code.replace("var","<span style='color:dodgerblue'>var</span>");
code = code.replace(/"(.*?)"/g,"<span style='color:green'>"$1"</span>");
code = code.replace(/<(.*?)>/g,"<span style='color:#F90'><$1></span>");
elem.innerHTML = code;
}
setInterval(Color,1000)
Thanks!
If the issue you're having is the cursor moving around while editing, you can fix that by grabbing the position of the cursor and putting it back at the end of the function. Do that by getting the selectionStart property of your editor textbox and then setting the selectionEnd property to that value after running the replacement.
Check out this answer for more information about selectionStart and selectionEnd.
Here's a simple code snippet from this answer that should get you rolling.
document.getElementById('target').addEventListener('input', function (e) {
var target = e.target,
position = target.selectionStart; // Capture initial position
target.value = target.value.replace(/\s/g, ''); // This triggers the cursor to move.
target.selectionEnd = position; // Set the cursor back to the initial position.
});
<p>The method <code>.replace()</code> will move the cursor's position, but you won't notice this.</p>
<input type="text" id="target" />
This issue is coming as the textContent of editor id being equated to its innerHTML. So change the variable name like the JS code I was written here :
function UnColor() {
var elem = document.getElementById("editor");
var text = elem.textContent;
var elem2;
elem2.innerHTML = text;
}
function Color() {
UnColor();
var elem = document.getElementById("editor");
var code = elem.innerHTML;
code = code.replace("var","<span style='color:dodgerblue'>var</span>");
code = code.replace(/"(.*?)"/g,"<span style='color:green'>"$1"</span>");
code = code.replace(/<(.*?)>/g,"<span style='color:#F90'><$1></span>");
var elem2;
elem2.innerHTML = code;
}
setInterval(Color,1000)
I make HTML file and js file but i had some problems.
In HTML there are 5 labels tag(and there's no specific id or class name) and when i click each label, pop-up(prompt) appear, and it make result(change style).
Changing style is not difficult so i am okay but i have a problem in prompt.
I wrote this code:
function changeCol(evnt) {
var theEvent = evnt ? evnt : window.event;
var label = document.getElementsByTagName("label");
label[0].addEventListener ("click", function (){
var one = prompt("Enter the color");
label[0].style.color = one;
});
label[1].addEventListener ("click", function (){
var two = prompt("Enter the color");
label[1].style.color = two;
});
label[2].addEventListener ("click", function (){
var three = prompt("Enter the color");
label[2].style.color = three;
});
}
But when i click a label first, it is okay buy when i click 2nd prompt appear twice... and 3rd click show prompt three times...
And when i want to see prompt i have to click twice and maybe it is because of function. In js there.
function loadevent(){ ...
if (label){
for (i=0;i < label.length; i++){
label[i].onclick = changeCol;
}
}
}
What should i do?
Hi try using the below code snippet:-
var label = document.getElementsByTagName("label");
function changeCol(element) {
element.addEventListener ("click", function (){
var promcolor= prompt("Enter the color");
element.style.color = promcolor;
});
}
function loadevent(){
if (label){
for (i=0;i < label.length; i++){
changeCol(label[i]);
}
}
}
loadevent();
And I assumed below HTML
<p><label for="1">label-1</label></p>
<p><label for="2">label-2</label></p>
<p><label for="3">label-3</label></p>
I dont see much use of loadevent function . But seeing the dots I assume there is some other code there. But if its not you can simply have one function like below:
function loadevent(){
for (itr=0;itr < label.length; itr++){
label[itr].addEventListener ("click", function (){
var promcolor= prompt("Enter the color");
this.style.color = promcolor;
});
}
}
Also the issue with your code was even while you iterate the element in loadevent function you add event listeners for all labels. This wont happen with this code.
Problem:
The problem with your actual code is that for each label you use this label's index and loop according to this index an alert a prompt, that's why you get only one prompt with the first label, two prompts with the second and three with the third label.
Solution:
The best approach is to use addEventListener like in your first function and loop through all labels using document.getElementsByTagName("label")and use this keyword to change color of the clicked label inside the loop, here's what you need :
var labels = document.getElementsByTagName("label");
for (i = 0; i < labels.length; i++) {
labels[i].addEventListener("click", function() {
var prmt = prompt("Enter the color");
this.style.color = prmt;
});
}
<label> A</label><br>
<label> B</label><br>
<label> C</label><br>
<label> D</label><br>
<label> E</label><br>
Note:
Using this code you don't need to specify any id or class or other attribute to your labels.
And then you just need to put this code inside your load function and call it in windows load:
function loadevent(){
var labels = document.getElementsByTagName("label");
for (i = 0; i < labels.length; i++) {
labels[i].addEventListener("click", function() {
var prmt = prompt("Enter the color");
this.style.color = prmt;
});
}
]
here you have written script of opening prompt in for loop hence it generate multiple popup depending on label number. i.e if you clicked on 4th label then it will open prompt 4 times.
To avoid this you have to pass index of current label.
function loadevent(){
if (label){
for (i=0;i < label.length; i++){
label[i].onclick = changeCol(i);
}
}
}
function changeCol(index,evnt) {
var theEvent = evnt ? evnt : window.event;
var label = document.getElementsByTagName("label");
label[index].addEventListener ("click", function (){
var current_color = prompt("Enter the color");
label[index].style.color = current_color;
});
}
This may helps you.
so i've got this script:
window.onload = function() {
var myValues = localStorage.getItem("myValues") ? JSON.parse(localStorage.getItem("myValues")) : [];
var myTables = localStorage.getItem("tableValues") ? JSON.parse(localStorage.getItem("tableValues")) : [];
makeDuplicates(myTables);
var divElements = document.querySelectorAll("#namefield");
for(var i = 0; i < myValues.length; i++) {
alert("In table: " + divElements[i].textContent + ", trying to change: "+myValues[i]);
divElements[i].textContent = myValues[i];
}
}
I did a little test with alert, the element it gets is right and myValue[i] exists but the value in div does not change with the code below alert. I don't know what else should i show in this occasion or is this enough?
As for more clarification - the similar code works in another javascript i'm using for another .html and this particular page loads the table in which i have td which content will be changed before the for cycle starts (got it with alert).
Any ideas why the change does not occur?
Added images for clarification:
This is a link to a HTML: http://pastebin.com/x5sbbj6b