qwertyuiop qwertyuiop - 2 months ago 7
Javascript Question

open website with drop into textbox HTML

I have made A user-script ( DOM Javascript) which included a text-box. I want the text-box to open up a google search of the input when an item is dropped. For example, if I select the word "Javascript" and drag it into the text-box, it will open up a Google search of "Javascript".

This is the code I have:

//only Javascript
var input2=document.createElement("input");
input2.type="text";
input2.id="Word_search";
input2.addEventListener("drop", GoogleWord);
document.body.appendChild(input2);

function GoogleWord(){
console.log("hi");
var text = document.getElementById("Word_search").value;
alert(text);
window.open('https://www.google.com/search?q=' + text,'_blank');
}


(I could not use a snippet because It does not seem to work inside the snippet)

The Main problem is that the function runs before the text is inserted into the textbox, and therefore, will do a blank Google search.

So, I only need the text to be inside the text-box when the function runs.

Answer

The drop event apparently occurs before the input is updated with the dropped text. The way to get the dropped text is with event.dataTransfer.getData(mimetype).

function GoogleWord(event){
    console.log("hi");
    var text = event.dataTransfer.getData('text/plain');
    alert(text);
    window.open('https://www.google.com/search?q=' + text,'_blank');
}

FIDDLE