Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draggable and Clickable input element using jquery

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

  • When I drag my input element, entire draggable div should be dragged. (Accomplished)
  • When I click on the input element, I should be able to edit the text. (Could not accomplish)

So, could some one tell me how to click and edit the text of an input element which is draggable as well?

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>
like image 763
Quick_Silver Avatar asked Dec 14 '25 06:12

Quick_Silver


2 Answers

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

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

like image 141
mtl Avatar answered Dec 16 '25 23:12

mtl


You could dispatch event, e.g:

-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)
    }
});
like image 24
A. Wolff Avatar answered Dec 16 '25 23:12

A. Wolff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!