Ok I have the following code which works fine when dragging and dropping the image into a box.
function drop(e) {
e.stopPropagation();
e.preventDefault();
var filesArray = event.dataTransfer.files;
for (var i=0; i<filesArray.length; i++)
{
var progressDiv = document.getElementById('progressDiv');
var pbar = document.createElement('progress');
var br = document.createElement('br');
var report = document.createElement('div');
pbar.setAttribute('id', 'progressBar' + i);
pbar.setAttribute('value', '0');
pbar.setAttribute('max', '100');
report.setAttribute('id', 'report' + i)
progressDiv.appendChild(pbar);
progressDiv.appendChild(br);
progressDiv.appendChild(report);
progressDiv.appendChild(br);
sendFile(filesArray[i]);
}
}
However when I change the code slightly to try and upload it if a user manually click the input type file button it for odd reason does not run.
function handleFiles(e) {
e.stopPropagation();
e.preventDefault();
var files = document.getElementById("ppupload").files[0];
alert(files);
var filesArray = files;
for (var i=0; i<filesArray.length; i++)
{
var progressDiv = document.getElementById('progressDiv');
var pbar = document.createElement('progress');
var br = document.createElement('br');
var report = document.createElement('div');
pbar.setAttribute('id', 'progressBar' + i);
pbar.setAttribute('value', '0');
pbar.setAttribute('max', '100');
report.setAttribute('id', 'report' + i)
progressDiv.appendChild(pbar);
progressDiv.appendChild(br);
progressDiv.appendChild(report);
progressDiv.appendChild(br);
sendFile(filesArray[i]);
}
}
Is there away to make this get the file and submit it?
fixed the issue by removing the for loop
function handleFiles(e) {
e.stopPropagation();
e.preventDefault();
var filesArray = document.getElementById("ppupload").files[0];
var progressDiv = document.getElementById('progressDiv');
var pbar = document.createElement('progress');
var br = document.createElement('br');
var report = document.createElement('div');
pbar.setAttribute('id', 'progressBar' + i);
pbar.setAttribute('value', '0');
pbar.setAttribute('max', '100');
report.setAttribute('id', 'report' + i)
progressDiv.appendChild(pbar);
progressDiv.appendChild(br);
progressDiv.appendChild(report);
progressDiv.appendChild(br);
sendFile(filesArray[i]);
}
Related
I have a website that triggers an alert when items are added to the cart. I'm using javascript ES6, html5.
I'm dynamically creating bootstrap styled cards with menu items on the page and a add to cart button. when the add to cart button is pressed an alert is triggered.
The alert attempts to trigger on iOS 13.x.x safari but doesn't show. I attempted to set a timeout, but that didn't work. It has to be the way it's being called. I really don't know what to try next. I read that user navigation (back, forward) can break alerts. In the 'addEventListener' of the 'btn' towards the bottom of this horrific method is where the problem arises. Why is this not working on safari mobile?
createMenuCard(menu){
var heading = document.getElementById("concession-name");
heading.innerText = menu.menus.menu.concessionName;
var card = null;
var body = null;
var lsgroup = null;
for(var i = 0; i < menu.menus.menu.categories.length; i++){
for(var j = 0; j < menu.menus.menu.categories[i].menuItems.length; j++){
this.card = document.createElement('div');
this.card.className = 'card';
this.card.setAttribute('id', this.uuidv4());
this.card.setAttribute('style', 'width: 20rem;');
this.body = document.createElement('div');
this.body.className = 'card-body';
var title = document.createElement('div');
title.className = 'card-title';
title.innerText = menu.menus.menu.categories[i].menuItems[j].name;
this.body.appendChild(title);
this.lsgroup = document.createElement('div');
this.lsgroup.className = "list-group";
this.body.appendChild(this.lsgroup);
for(var k = 0; k < menu.menus.menu.categories[i].menuItems[j].subItems.length; k++){
if(menu.menus.menu.categories[i].menuItems[j].subItems[k].name === "")
{
var id = this.uuidv4();
var input = document.createElement("input");
input.setAttribute("type", "checkbox");
input.setAttribute("name", "");
input.setAttribute("id", id);
input.setAttribute("value", menu.menus.menu.categories[i].menuItems[j].name);
input.setAttribute("price", menu.menus.menu.categories[i].menuItems[j].subItems[k].price);
this.lsgroup.appendChild(input);
// label
var label = document.createElement("label");
label.className = "list-group-item";
label.setAttribute("for", id);
label.innerText = menu.menus.menu.categories[i].menuItems[j].subItems[k].price + " " + menu.menus.menu.categories[i].menuItems[j].name;
this.lsgroup.appendChild(label);
}
else
{
var id = this.uuidv4();
// input
var input = document.createElement("input");
input.setAttribute("type", "checkbox");
input.setAttribute("name", "");
input.setAttribute("id", id);
input.setAttribute("value", menu.menus.menu.categories[i].menuItems[j].subItems[k].name);
input.setAttribute("price", menu.menus.menu.categories[i].menuItems[j].subItems[k].price);
this.lsgroup.appendChild(input);
// label
var label = document.createElement("label");
label.className = "list-group-item";
label.setAttribute("for", id);
label.innerText = menu.menus.menu.categories[i].menuItems[j].subItems[k].price + " " +menu.menus.menu.categories[i].menuItems[j].subItems[k].name;
this.lsgroup.appendChild(label);
}
}
var btn = document.createElement('a');
btn.setAttribute("href", "#"); // javascript:toCart()
btn.addEventListener("click", (e)=> {
var inputs = e.path[2].querySelector("div > div.list-group").getElementsByTagName("input");
var description = e.path[2].querySelector("div > div.card-title").innerText;
for(var l = 0; l < inputs.length; l++){
if(inputs[l].checked === true){
var obj = {
option : inputs[l].value,
price : inputs[l].getAttribute("price")
};
setTimeout(function(){
window.alert("Added: " + description + " to cart");
}, 300);
//window.alert("Added: " + description + " to cart");
description += " " + obj.option;
var appItem = new AppItems(description, obj.price, 1);
cart.addItem(appItem);
}
}
});
btn.className = "btn btn-primary";
btn.innerText = "Add To Cart";
this.body.appendChild(btn);
this.card.appendChild(this.body);
var container = document.getElementById('cards');
container.appendChild(this.card);
}
}
var chk = document.getElementById("checkout");
chk.addEventListener("click", (e)=> {
cart.save();
window.open("./cart.html","_self");
});
}
::UPDATED CODE::
I have dynamically generated buttons from an array. When a button is clicked, 10 still images of gifs append to the page from an API call. When clicking on one of the dynamically generated still images, I need the animated gif to display. Upon clicking again, I need the still image to show and the animated gif to hide.
lastClick = [];
var killersGifs = {
killerSearches: ["Freddy Krueger", "Jason Voorhees", "Pennywise", "Ghostface", "American Mary", "Chucky", "Bride of Chucky", "The Candyman", "Cujo", "Hannibal", "Leatherface", "Michael Myers", "Norman Bates", "Pinhead"],
buttonLoop: function() {
for (var b = 0; b < killersGifs.killerSearches.length - 1; b++) {
var buttonM = $("<button class='dynGen'>").text(killersGifs.killerSearches[b]).attr("data-index", killersGifs.killerSearches[b]);
$("#buttons").append(buttonM);
}
},
divLoop: function(click) {
var queryURL = "https://api.giphy.com/v1/gifs/search?api_key=B26sstJns2pZuNT5HiJpqS5FV8Su1sDd&q=" + lastClick + "&limit=10"
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
console.log(response.data);
for (var i = 0; i < response.data.length; i++) {
var respData = response.data[i];
var image = respData.images.fixed_height_small_still.url;
var gif = respData.images.fixed_height_small.url;
var rating = respData.rating;
var dynDiv = $("<div class='dyn-div'>");
//dynDiv.attr("data-index", i);
var killerImg = $("<img class='still-image'>");
killerImg.attr("src", image);
killerImg.attr("alt", "Serial Killer still frame of gif");
killerImg.attr("data-gif", gif);
killerImg.attr("class", "killerImg");
killerImg.attr("data-index", i);
dynDiv.append("<p> Rating: " + rating + "</p>");
dynDiv.append(killerImg);
$("#append-img-div").prepend($(dynDiv));
};
});
},
userPush: function () {
var userInput = $("input[type='text']").val().trim();
console.log(userInput);
killersGifs.killerSearches.push(userInput);
var buttonU = $("<button class='dynGen'>").text(userInput).attr("data-index", userInput);
$("#buttons").append(buttonU);
console.log(killersGifs.killerSearches);
}
};
killersGifs.buttonLoop();
$("#killer-add-submit").on("click", function(event) {
event.preventDefault();
killersGifs.userPush();
});
$(document).on("click", "button.dynGen", function(event) {
var currentIndex = $(this).attr("data-index");
lastClick.push(currentIndex);
console.log(currentIndex);
event.preventDefault();
$("#append-img-div").empty();
killersGifs.divLoop();
lastClick = [];
});
$(document).on("click", ".killerImg", function(event) {
console.log("test");
var currentIn = $(this).attr("data-index");
var tempUrl = $(this).attr("data-gif");
console.log(currentIn);
console.log(tempUrl);
});
On click, the clicked image should toggle between still image and animated gif.
Click function console logs index and correct gif URL of clicked image. I am not sure how to incorperate that to swap the gif and image on click.
I think you need to set the gif url as a property of the img element you are creating with jQuery. Something like:
`killerImg.attr("data-gif", gif);`
seeing as you already defined
var gif = respData.images.fixed_height_small.url;. You may also want to give it a unique id like:
killerImg.attr("id", "killer-img");
Then, in your on click event you can retrieve that attribute from the element itself:
var tempUrl = $("#killer-img").attr("data-gif");
and switch it out with the img src with:
$("#killer-img").attr("data-gif") = $("#killer-img").attr("src");
and finally:
$("#killer-img").attr("src") = tempUrl to set the image source to the moving gif.
I recently tackled a very similar assignment myself. Hope this helps!
lastClick = [];
var killersGifs = {
killerSearches: ["Freddy Krueger", "Jason Voorhees", "Pennywise", "Ghostface", "American Mary", "Chucky", "Bride of Chucky", "The Candyman", "Cujo", "Hannibal", "Leatherface", "Michael Myers", "Norman Bates", "Pinhead"],
buttonLoop: function() {
for (var b = 0; b < killersGifs.killerSearches.length - 1; b++) {
var buttonM = $("<button class='dynGen'>").text(killersGifs.killerSearches[b]).attr("data-index", killersGifs.killerSearches[b]);
$("#buttons").append(buttonM);
}
},
divLoop: function(click) {
var queryURL = "https://api.giphy.com/v1/gifs/search?api_key=B26sstJns2pZuNT5HiJpqS5FV8Su1sDd&q=" + lastClick + "&limit=10"
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
console.log(response.data);
for (var i = 0; i < response.data.length; i++) {
var respData = response.data[i];
var image = respData.images.fixed_height_still.url;
var gif = respData.images.fixed_height.url;
var rating = respData.rating;
var dynDiv = $("<div class='dyn-div'>");
//dynDiv.attr("data-index", i);
var killerImg = $("<img class='still-image'>");
killerImg.attr("src", image);
killerImg.attr("alt", "Serial Killer still frame of gif");
killerImg.attr("data-gif", gif);
killerImg.attr("class", "killerImg");
killerImg.attr("data-index", i);
killerImg.attr("data-img", image);
dynDiv.append("<p> Rating: " + rating + "</p>");
dynDiv.append(killerImg);
$("#append-img-div").prepend($(dynDiv));
};
});
},
userPush: function () {
var userInput = $("input[type='text']").val().trim();
killersGifs.killerSearches.push(userInput);
var buttonU = $("<button class='dynGen'>").text(userInput).attr("data-index", userInput);
$("#buttons").append(buttonU);
console.log(killersGifs.killerSearches);
}
};
killersGifs.buttonLoop();
$("#killer-add-submit").on("click", function(event) {
event.preventDefault();
killersGifs.userPush();
});
$(document).on("click", "button.dynGen", function(event) {
var currentIndex = $(this).attr("data-index");
lastClick.push(currentIndex);
console.log(currentIndex);
event.preventDefault();
$("#append-img-div").empty();
killersGifs.divLoop();
lastClick = [];
});
$(document).on("click", ".killerImg", function(event) {
console.log("test");
//killersGifs.animateGif();
var currentIn = $(this).attr("data-index");
var tempUrl = $(this).attr("data-gif");
var tempUrl2 = $(this).attr("data-img");
console.log(currentIn);
console.log(tempUrl);
if ($(this).attr("src") == tempUrl2) {
$(this).attr("src", tempUrl);
}
else if ($(this).attr("src") == tempUrl) {
$(this).attr("src", tempUrl2);
};
});
I am working on a simple drag and drop operation in JS. I have to generate the containers, since I do not know in advance how many I will need, and that seems to be leading to a couple of problems.
The first is that if I drag an item over the last div, the div disappears. I have no idea what is causing it, but it is odd.
The second is that in the drop section
box.addEventListener('drop', function(e) {
e.preventDefault();
var data = e.dataTransfer.getData('id');
e.target.appendChild(document.getElementById(data));
});
I am getting the error message: "Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'," and the 'data' is not being passed. I only get this message on JSFiddle: in both Firefox and Chrome it works fine, but I suspect that it is part of a larger issue.
I am very new at this, so any help would be appreciated.
JSFiddle here.
I think this will work for you.
I've made some changes to your javascript.
Please have a look here:
var productList = [];
for (var w = 0; w < 2; w++) {
productList.push('Apples', 'Plums', 'Rice', 'Potatoes', 'Chicken', 'Pork');
}
productList.sort();
console.log(productList.length);
var boxContainer = document.createDocumentFragment();
for (var i = 0; i < 3; i++) {
var box = boxContainer.appendChild(document.createElement("div"));
var boxID = "box" + i;
box.setAttribute('id', boxID);
box.setAttribute('class', 'dropTarget');
box.addEventListener('dragend', function(e) {
elementDragged = null;
});
box.addEventListener('dragover', function(e) {
if (e.preventDefault) {
e.preventDefault();
};
//This close was right below your Remove Class. Preventing the over class from being added
});
box.addEventListener('dragenter', function(e) {
if(this.className.indexOf('over') < 0)
//Append the className, don't remove it.
this.className += " over";
});
box.addEventListener('dragleave', function(e) {
//Now we remove it.
this.className = this.className.replace(' over','');
e.dataTransfer.dropEffect = 'move'
return false;
});
box.addEventListener('drop', function(e) {
e.preventDefault();
var data = e.dataTransfer.getData('id');
//Just preventing the HierarchyRequestError.
var parent= e.dataTransfer.getData('parent');
if(parent == e.target.id) return;
target=e.target;
//Prevent it from dragging into another div box and force it to go into the box.
if(e.target.id.indexOf('box') < 0 ) target=e.target.parentNode;
target.appendChild(document.getElementById(data));
});
document.drag = function(target, e) {
e.dataTransfer.setData("Text", 'id');
//This is the drag function that's being called. It needed the reference to the ID.
e.dataTransfer.setData('id', target.id);
//Add parentID, so we can check it later.
e.dataTransfer.setData('parent',target.parentNode.id)
}
document.getElementById("placeholder").appendChild(box);
};
for (var a = 0; a < productList.length; a++){
renderProductList(productList[a], a);
};
function renderProductList(element, index) {
console.log(element);
var nameDiv = document.createElement('div');
var itemName = element;
nameDiv.setAttribute('class','dragger');
nameDiv.setAttribute('id', itemName + index);
nameDiv.setAttribute('name', itemName);
nameDiv.setAttribute('draggable', "true");
nameDiv.setAttribute('ondragstart', 'drag(this, event)');
nameDiv.style.backgroundColor = pastelColors();
var aBox = document.getElementById('box0');
aBox.appendChild(nameDiv);
var t = document.createTextNode(element);
console.log("T: " + t);
nameDiv.innerHTML = nameDiv.innerHTML + element;
};
function pastelColors(){
var r = (Math.round(Math.random()* 127) + 127).toString(16);
var g = (Math.round(Math.random()* 127) + 127).toString(16);
var b = (Math.round(Math.random()* 127) + 127).toString(16);
pColor = '#' + r + g + b;
console.log(pColor);
return pColor;
};
function drag(target, e) {
e.dataTransfer.setData('id', target.id);
};
https://jsfiddle.net/3yLk11eb/5/
I've made comments everywhere I made changes. And there were a lot of changes to make this work smoothly.
Here id my code. I want to append 4 buttons inside the specific div. In the other words, I want to put these 4 buttons inside ''. Now it works but they are not inside the div.
getmyItems function is a function that contains an array of information like: title, description , age ,... .
Help
getmyItems(param, function(data) {
var mtItem = JSON.stringify(data);
myItem = JSON.parse(mtItem);
var Item = document.getElementById('myItems');
for (var i = 0; i < myItem.results.length; i++) {
var buffer = "";
buffer += '<div class="act-time">';
buffer += '<div class="activity-body act-in">';
buffer += '<span class="arrow"></span>';
buffer += '<div class="text">';
buffer += '<p class="attribution">';
buffer += ''+myItem.results[i].title+'';
buffer += myItem.results[i].description;
buffer += '</p>';
buffer += '</div>';
buffer += '</div>';
buffer += '</div>';
var div = document.createElement('div');
div.innerHTML = buffer;
//var elem = div.firstChild;
Item.appendChild(div);
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'btn btn-danger');
btn.value = "Delete";
btn.onclick = (function(i) {
return function() {
var c=confirm('Are you Sure? ');
if (c==true)
doDelete(myItem.results[i].item_id);
};
})(i);
Item.appendChild(btn);
var show_btn=document.createElement('input');
show_btn.setAttribute('type','button');
show_btn.setAttribute('class','btn btn-primary');
show_btn.value="ShowInDetail";
show_btn.onclick=(function(i){
return function(){
showInDetail(myItem.results[i]);
window.location='showInDetail.html';
};
})(i);
Item.appendChild(show_btn);
var extend_btn=document.createElement('input');
extend_btn.setAttribute('class','btn btn-warning');
extend_btn.setAttribute('type','button');
extend_btn.value="Extend";
extend_btn.onclick=(function(i){
return function(){
extendItem(myItem.results[i]);
window.location='extendItem.html';
};
})(i);
Item.appendChild(extend_btn);
var bookmark=document.createElement('input');
bookmark.setAttribute('type','button');
bookmark.setAttribute('class','btn btn-primary');
bookmark.value='Bookmark';
bookmark.onclick=(function(i){
return function(){
var p={user_id:localStorage.getItem('user_id')};
window.localStorage.setItem('this_item_id', myItem.results[i].item_id);
getBookmarks(p, function(d){
var bk=JSON.stringify(d);
bk=JSON.parse(bk);
if(bk.results){
var l=0;
for(var j in bk.results){
if(bk.results[j].item_id==localStorage.getItem('this_item_id')){
removeBookmark(bk.results[j]);
l=1;
}
}if(l==0){
addBookmark(myItem.results[i]);
}
}else{
addBookmark(myItem.results[i]);
}
});
};
})(i);
Item.appendChild(bookmark);
//document.getElementById(i).appendChild(btn);
}
});
In what specific div do you want them? So far, in this way the four buttons are inside the myItens div see in the fiddle and in the code below.
var getmyItems = function(data) {
var item = document.getElementById('myItems');
for (var i = 0; i < data.length; i++) {
var result = data[i];
// creation of the buffer outer div
var buffer = document.createElement('div');
buffer.className = 'act-time';
//creation of de activity-body
var activity = document.createElement('div');
activity.className = 'activity-body act-in';
//creation of the first span
var arrow = document.createElement('span');
arrow.className = 'arrow';
//creation of the most inner div
var textDiv = document.createElement('div');
textDiv.className = 'text';
//creation of the content of the most inner div
var attribution = '';
attribution += '<p class="attribution">';
attribution += '' + result.title + '';
attribution += result.description;
attribution += '</p>';
//initialize the text div
textDiv.innerHTML = attribution;
//put the arrow span inside the activity div
activity.appendChild(arrow);
// put the text div inside the activity div
activity.appendChild(textDiv);
//put the activity inside the buffer div
// each time appendChild is applied the element is attach tho the end of the target element
buffer.appendChild(activity);
var div = document.createElement('div');
div.appendChild(buffer);
item.appendChild(div);
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'btn btn-danger');
btn.value = "Delete";
btn.onclick = (function(i) {
return function() {
var c = confirm('Are you Sure? ');
if (c === true) {
//do something;
};
};
})(i);
// now that all div are created you can choose which div you want to put the button inside.
// in this I chose the buffer.
buffer.appendChild(btn);
var showBtn = document.createElement('input');
showBtn.setAttribute('type', 'button');
showBtn.setAttribute('class', 'btn btn-primary');
showBtn.value = "ShowInDetail";
showBtn.onclick = (function(i) {
return function() {
window.location = 'showInDetail.html';
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(showBtn);
var extendBtn = document.createElement('input');
extendBtn.setAttribute('class', 'btn btn-warning');
extendBtn.setAttribute('type', 'button');
extendBtn.value = "Extend";
extendBtn.onclick = (function(i) {
return function() {
window.location = 'extendItem.html';
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(extendBtn);
var bookmark = document.createElement('input');
bookmark.setAttribute('type', 'button');
bookmark.setAttribute('class', 'btn btn-primary');
bookmark.value = 'Bookmark';
bookmark.onclick = (function(i) {
return function() {
var p = { user_id: localStorage.getItem('user_id') };
window.localStorage.setItem('this_item_id', myItem.results[i].item_id);
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(bookmark);
}
};
var myItem = [{ title: 'person', description: 'familyName' }, { title: 'ohterPerson', description: 'otherFamilyName' }];
getmyItems(myItem);
I am trying to write a click event for an anchor tag in my tampermonkey script.
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;
contentTag.innerHTML = "";
var lines = fileContents.split("\n");
window.alert("Number of lines:"+lines.length);
for(var i=0; i<20; i++) {
if(i!==15)
contentTag.innerHTML+=(lines[i]+"<br>");
else {
contentTag.innerHTML+=("<a id=link1>Click me</a>");
var link = document.getElementById('link1');
link.addEventListener("click", function() {
window.alert('I am clicked');
}, false);
}
}
The alert message never gets triggered when I click on the link in the page dispalyed, even though I have a a click event listener defined. What am I doing wrong here?
It's the way you're adding HTML, you're reappending the link when you do this in the next iteration.
link.innerHTML += something
So the event handler is lost, and you can actually prove that by adding the event handler to the last element instead.
If you do it the proper way, creating elements and appending them, it works fine
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;
contentTag.innerHTML = "";
var lines = fileContents.split("\n");
for (var i = 0; i < 20; i++) {
if (i !== 15) {
var txt = document.createTextNode(lines[i] || ''),
br = document.createElement('br');
contentTag.appendChild(txt);
contentTag.appendChild(br);
} else {
var link = document.createElement('a');
link.id = 'link1';
link.innerHTML = 'Click me';
link.addEventListener("click", function () {
alert('clicked')
}, false);
contentTag.appendChild(link)
}
}
FIDDLE
Shoud be contentTag.innerHTML+=("<a id='link1'>Click me</a>");
Try this:
<script>
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;
contentTag.innerHTML = "";
var lines = fileContents.split("\n");
window.alert("Number of lines:"+lines.length);
for(var i=0; i<20; i++) {
if(i!==15)
contentTag.innerHTML+=(lines[i]+"<br>");
else {
contentTag.innerHTML+=("<a id=link"+i+">Click me</a>");
var link = document.getElementById('link'+i);
var att=document.createAttribute('onclick');
att.value="alert('Clicked !')";
link.setAttributeNode(att);
}
}
</script>
Demo: http://jsfiddle.net/TmJ38/