Reputation: 1
I want to generate an img tag like this with javascript:
<img id="drag0" src="http://localhost:34737/Images/MainSlider/A(1).jpg" class="col-4" draggable="true" ondragstart="drag(event)">
and drag method:
document.addEventListener("drag", function (ev) {
ev.dataTransfer.setData("text", ev.target.id);
}, false);
When I generate the dynamic html it's not working as expected and it returns this in the DOM:
<img id="drag1" src="http://localhost:34737/Images/MainSlider/B(1).jpg" class="col-4" draggable="true" ondragstart="function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);}">
This is my javascript code:
var img = document.createElement("img");
img.setAttribute("id", "drag" + i);
img.setAttribute("src", user[i].MainPicAddress);
img.setAttribute("class", "col-" + e);
img.setAttribute("draggable", true);
img.setAttribute("ondragstart", drag);
Upvotes: 0
Views: 270
Reputation: 1071
try adding double quotes around the setAttribute 2nd parameter.
img.setAttribute("ondragstart", 'drag(event)');
or something like
img.setAttribute("ondragstart", 'drag');
Upvotes: 0
Reputation: 12880
You need to put your ondragstart
attribute value in quotes like this :
img.setAttribute("ondragstart", "drag(event)");
Upvotes: 1