user1797147
user1797147

Reputation: 927

javascript dragging the div code will froze the input text

I use this code for dragging a DIV, which is a small information box. Within, I have some simple HTML including a input text or similar. When enabling the drag (see code) all inputs are frozen.

var selected = null, // Object of the element to be moved
    x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
    x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element

// Will be called when user starts dragging an element
function _drag_init(elem) {
    // Store the object of the element which needs to be moved
    selected = elem;
    x_elem = x_pos - selected.offsetLeft;
    y_elem = y_pos - selected.offsetTop;
}

// Will be called when user dragging an element
function _move_elem(e) {
    x_pos = document.all ? window.event.clientX : e.pageX;
    y_pos = document.all ? window.event.clientY : e.pageY;
    if (selected !== null) {
        selected.style.left = (x_pos - x_elem) + 'px';
        selected.style.top = (y_pos - y_elem) + 'px';
    }
}

// Destroy the object when we are done
function _destroy() {
    selected = null;
}

document.onmousemove = _move_elem;
document.onmouseup = _destroy;

There is a bigger code here, so I will simplify:

div = document.getElementById("mydiv");

    div.onmousedown = function () {
        _drag_init(this);
        return false;
    };

Now when I display the DIV, the drag works smoothly (FF 53) but any input elements within are frozen :)

The content of my infobox (the DIV) is simple

<input id="input_text" type="text" name="product" list="productName"/>
<datalist id="productName">
    <option value="Pen">Pen</option>
    <option value="Pencil">Pencil</option>
    <option value="Paper">Paper</option>
</datalist><br> <button id="myNiceButton" action="input_text">OK</button>

I already tried bunch of solutions from StackOverflow without success, including eg. this one

Prevent drag event to interfere with input elements in Firefox using HTML5 drag/drop

<div draggable="true" id="draggableDiv">
    <textarea onfocus="onFocus();" onblur="onBlur();">Inside draggable (FIXED)</textarea>
</div>

But seems that those events are not triggered at all. Also tried draggable="false" but the same story, not working.

What will be the problem?

Upvotes: 0

Views: 52

Answers (1)

yo3hcv
yo3hcv

Reputation: 1669

Actually the drag code is fine.

div.onmousedown = function () {
    _drag_init(this);
    return false; // <-- remove this
};

Or play with preventdefault() which one suits best.

event.preventDefault() vs. return false

return false here will prevent any mouse "down" so I guess it's impossible to click in input text with the mouse, acting like "disabled".

Upvotes: 1

Related Questions