qwertyuiop qwertyuiop - 10 months ago 51
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.addEventListener("drop", GoogleWord);

function GoogleWord(){
var text = document.getElementById("Word_search").value;
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 Source

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){
    var text = event.dataTransfer.getData('text/plain');
    window.open('https://www.google.com/search?q=' + text,'_blank');