Why is my remove event listener not functioning?

I know that similar questions were already answered on stack but for some reason their solutions don’t work for me. I am trying to create a simple drag and drop game/activity. User can have only one attempt to drag an element, so if it dragged once I want to remove associated drag event listeners. Hope it makes sense. And here is the code:


<div id="boxes">
 <div id="b1" class="box" draggable="true"><header>Vacuum Tubes</header></div>
 <div id="b2" class="box" draggable="true"><header> Eniac</header></div> 
 <div id="b3" class="box" draggable="true"><header> Transistors </header> </div> 
 <div id="b4" class="box" draggable="true"><header> Integrated Cicuits</header> </div>
 <div id="b5" class="box" draggable="true"><header> Microprocessor </header> </div>

In the init function I am adding the event listeners to the elements I want to drag later on.

function init(){
 cols = document.querySelectorAll('#boxes div.box');
 [].forEach.call(cols, function(col) {
 col.addEventListener('dragstart', handleDragStart, false);
 col.addEventListener('dragend', handleDragEnd, false);}

**** boxes, states and cols are arrays that are defined and declared outside the init() function

Than in the function that handles dropping of the element I have the following code

dragSrcEl.removeEventListener('dragstart', handleDragStart, false);
dragSrcEl.removeEventListener('dragend', handleDragEnd, false);
cols[i].removeEventListener('dragstart', handleDragStart, false);
cols[i].removeEventListener('dragend', handleDragEnd, false);

So as you can see I am trying prevent this element from dragging in three different ways. And still, it doesn’t work. User can still drag the element.

My question 1:
how I can remove dragstart and dragend event listener ?
My question 2:
Why my code doesn’t work?


There is wide variation in behaviour among browsers. The only one I can think of that behaves the way you expect is Firefox.

The draggable attribute on its own is enough to allow drag on Internet Explorer, Edge and Chrome. Firefox on the other hand won’t enter drag mode until event.dataTransfer.setData(mimetype, valuestring) is called. For selected text and images this happens automatically, which is why they are magically draggable.

So for FF to set the value you must have a dragStart handler, and once you have a handler it must return true or you still won’t get drag mode.

To get uniform cross browser behaviour you must do it the FF way and set the value of draggable to indicate whether drag is to start, so as to suppress drag on IE, Edge and Chrome. Returning false might also work but you’ll have to check that.

Leave a Reply

Your email address will not be published. Required fields are marked *