Question

I am trying to apply querySelectorAll on Dynamic Content.
I am implementing the code like below:

<div class="drag" draggable="true">hello</div>
<div class="drop"></div>

These tags are created dynamically on the page. QuerySelectorAll not working on both of these tags.

            var cols = document.querySelectorAll('.drag');
        [].forEach.call(cols, function (col) {
            col.addEventListener('dragstart', handleDragStart, false);
            col.addEventListener('dragend', handleDragEnd, false);
        });

        var colss = document.querySelectorAll('.drop');
        [].forEach.call(colss, function (col) {
            col.addEventListener('dragenter', handleDragEnter, false)
            col.addEventListener('dragleave', handleDragLeave, false);
            col.addEventListener('dragover', handleDragOver, false);
            col.addEventListener('drop', handleDrop, false);
        });

My problem is that I am trying to apply code on these two div's but if these tags are static querySelectorAll is working but if I create these two div's dynamically they are not working.

I have applied this code from HTML5 Drag and Drop API reference[Link]: http://www.html5rocks.com/en/tutorials/dnd/basics/

Thanks in Advance...!!!

Was it helpful?

Solution

I resolved this using jQuery. Code below works best:

            $('body').on('dragstart', '.drgbl', function (e) {
            handleDragStart(e)
        });
        $('body').on('dragend', '.drgbl', function (e) {
            handleDragEnd(e)
        });
        $('body').on('dragenter', '.rght-element', function (e) {
            handleDragEnter(e)
        });
        $('body').on('dragleave', '.rght-element', function (e) {
            handleDragLeave(e)
        });
        $('body').on('dragover', '.rght-element', function (e) {
            handleDragOver(e)
        });
        $('body').on('drop', '.rght-element', function (e) {
            handleDrop(e)
        }); 

This jQuery code works very fine on the dynamic data as .on() works on handling dynamic data attaching handler very easily.

Thanks Everyone for me able to figure out the answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top