简体   繁体   中英

Access the `draggable` attribute with javascript

So the question is : How can you do that ? I want to change the draggable attribute to "false" so the element that was previously draggable will lose this property.

I will give you a div so you will have something to start with :

     <div id="div1"  draggable="true" ondragstart="drag(event) "onDblClick="edit('div1')">
     </div>
document.getElementById('div1').setAttribute('draggable', false);

OR

var elem = document.getElementById('div1');
elem.setAttribute('draggable', false);

If you want the attribute totally gone use;

elem.removeAttribute('dragable');

There is many ways, if you use jQuery :

    $('#div1').attr('dragabble'); //returns with the value of attribute
    $('#div1').attr('dragabble','false'); //sets the attribute to false

Native JS:

    document.getElementById('div1').getAttribute('draggable'); //returns the value of attr
    document.getElementById('div1').setAttribute('draggable', 'false'); //set the value of attr

You might want to use jquery-ui draggable component to acheive ur required functionality.. or if u have jquery library in ur Dev environment u can use the following code

$("#div1").attr('draggable',false);

or using javascript we can do it as follows

document.getElementById('div1').setAttribute('draggable', 'false');

After set the attribute draggable to true , you mostly often want to handle dragstart event. To do that in native JS:

elem.addEventListener('dragstart', ev => {
  // dragstart handlings here
  }, false)

I'm a little late to the party, but is there a reason why we wouldn't just want to write something like this?

var el = document.createElement('div');
el.draggable = false;

Seems to apply the attribute fine for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM