Draggable and clickable input element using jquery

I have an input element inside a divgable div. My code should do the following:

  • When I drag the input element, the entire dragged div needs to be dragged. (Implemented)
  • When I click on an input element, I should be able to edit the text. (Failed to execute)

So, can someone tell me how to click and edit the text of an input element that can also be dragged?

Here is my complete code:

<!DOCTYPE html>
<html>
    <head>
        <title>Draggable and Clickable Input</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="js/jquery.js"></script>
        <script src="js/jquery-ui.js"></script>
        <style>
            .draggable{height:500px;width:500px;background:blue;}
        </style>
    </head>
    <body>

        <div class="draggable" >
            <input type="text" value="drag me!"/>
        </div>

        <script>
            $('.draggable').draggable({
                cancel: ''
            });
        </script>

    </body>
</html>

      

+3


source to share


4 answers


$('.draggable input').click(function() {
    $(this).focus();
});

      



The input field is now editable and you can still drag the entire div from the input field. JSFiddle .

+3


source


You can send an event like:

-DEMO -



$(".draggable").draggable({
    start: function (event, ui) {
        $(this).data('preventBehaviour', true);
    }
});
$(".draggable :input").on('mousedown', function (e) {
    var mdown = document.createEvent("MouseEvents");
    mdown.initMouseEvent("mousedown", false, true, window, 0, e.screenX, e.screenY, e.clientX, e.clientY, true, false, false, true, 0, null);
    $(this).closest('.draggable')[0].dispatchEvent(mdown);
}).on('click', function (e) {
    var $draggable = $(this).closest('.draggable');
    if ($draggable.data("preventBehaviour")) {
        e.preventDefault();
        $draggable.data("preventBehaviour", false)
    }
});

      

+2


source


You can try adding an attribute contenteditable

to your div:

Html

<div contenteditable="true" class="draggable" >
    <input type="text" value="drag me!"/>
</div>

      

JQuery

$(".draggable").draggable()
  .click(function() {
    $(this).draggable( {disabled: false});
}).dblclick(function() {
    $(this).draggable({ disabled: true });
});

      

JSFiddle

0


source


Really old question, but I have a slightly different solution, so answering here.

Disable dragging on an element input

by setting the cancel attribute of the dragged initializer. I think this is a small compromise in most situations. But YMMV.

$(".card").draggable({
     cancel: "input"
});

      

0


source







All Articles