Run
Run

Reputation: 57176

draggable without jquery ui: how to stop dragging the not-draggable and type-able elements?

I have this draggable code without jquery ui and I want to modify it to suit my requirements:

  1. I don't want <p> tag or any inside <div> tag to be draggable.
  2. I need to be able to type in the input fields.

html,

<div>
    <p>not draggable</p>
    <input type="text" value="type-able"/>
</div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

I tried with these below but they don't work,

        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();

jquery,

$(function() {
    $('body').on('mousedown', 'div', function(e) {
        $(this).addClass('draggable').parents().on('mousemove', function(e) {

            $('.draggable').offset({
                top: e.pageY - $('.draggable').outerHeight() / 2,
                left: e.pageX - $('.draggable').outerWidth() / 2
            }).on('mouseup', function() {
                $(this).removeClass('draggable');
            });
        });
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
    }).on('mouseup', function() {
        $('.draggable').removeClass('draggable');
    });
});

any idea how I can do that?

css,

body {padding:50px;}

div {
  cursor:move;
  width:70px;
  height:70px;
  background-color:black;
  border:1px solid black;
  margin:2px;
  float:left;
}

.draggable {
  background-color:yellow;
}

p {
    border:1px solid red;
    background:white;
}

Upvotes: 0

Views: 95

Answers (1)

ElDoRado1239
ElDoRado1239

Reputation: 4048

Insert something like this right at the top of your drag function :

if(e.target.className == "dontDragMePlease") return;

Then add

classname="dontDragmePlease"

to every element you don't want to drag with that function.

Or:

if(e.target.tagName == 'INPUT') return;

Like this:

$('body').on('mousedown', 'div', function(e) {
 if(e.target.className == "dontDragMePlease") return;
 if(e.target.tagName == 'INPUT') return;
    $(this).addClass('draggable').parents().on('mousemove', function(e) {

Upvotes: 1

Related Questions