Creating Boxes that can be Drag and Drop Imported as Tiddlers

The code above is a tamper monkey script. TamperMonkey is a browser extension that allows you to run custom js on websites. That code creates a draggable box that can be dragged into TiddlyWiki as an import for a tiddler. Due to how TiddlyWiki is already set up, nothing needs to be done to enable you to drag a tiddler in.

You need to create the box to be dragged, and importantly set it to be draggable. In this case, I add some text to it.

var parent = quote.querySelector(".test");
const box = document.createElement("div");

box.setAttribute('draggable', true);

var text = document.createTextNode("Drag to TW");
box.appendChild(text);

You then need to create the data to be imported into TW. This is a list of fields (title, tags, and text being fields.) If you’re using this as part of a tamper monkey script, then these will likely need to be filled out dynamically with js.

var data = {
    title: "Hogfather",
    tags: "Books",
    author: "Terry Pratchett",
    published: "1996",
    text: "I really like this book"
}

Here is the important part. This adds the data to the dragged box. This is modified a bit from here, where they use a list of tiddlers instead of a single one.

box.addEventListener('dragstart', (event) => {
    event.dataTransfer.setData("URL","data:text/vnd.tiddler," + encodeURIComponent(JSON.stringify(data)));
    event.stopPropagation();
    return false;
});

You then need to actually add the box to the website. After this, you should be done.

parent.appendChild(box);

Here is a link where you can play with and test the code.

2 Likes