::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);
};
});
Related
I am making a gif generator, the goal being to dynamically create clickable buttons that will then dynamically add 10 gifs from the search term to the page. On click is returning the console log, but will not add divs with gif images and rating to the page.
HTML
<form id="killer-form">
<label for="killer-input">Add a serial killer:</label>
<input type="text" id="killer-input"><br>
<input id="killer-add-submit" type="submit" value="Submit">
</form>
<div id="append-img-div"></div>
JS
var killersGifs = {
killerSearches: ["Freddy", "Jason", "Pennywise", "Ghost Face", "American Mary", "Chucky", "Bride of Chucky", "Candyman", "Cujo", "Hannibal", "Leatherface", "Michael Meyers", "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(event) {
for (var i = 0; i < killersGifs.killerSearches.length - 1; i++) {
//console.log(this.killerSearches[i]);
//var newDiv = $("<div class='gif-div'>");
var killer = killersGifs.killerSearches[i];
var queryURL = "https://api.giphy.com/v1/gifs/search?api_key=B26sstJns2pZuNT5HiJpqS5FV8Su1sDd&q=" + killer + "&limit=10"
//console.log(queryURL);
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
console.log(response);
for (var x = 0; x < response.length - 1; x++) {
var respData = response[x].data;
var image = respData.images.fixed_height_small_still.url;
var rating = respData.rating;
var dynDiv = $("<div class='dyn-div'>");
var killerImg = $("<img>");
killerImg.attr("src", image);
killerImg.attr("alt", "Serial Killer still frame of gif");
dynDiv.append("Rating: " + rating);
dynDiv.append(image);
$("#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) {
event.preventDefault();
$("#append-img-div").empty();
killersGifs.divLoop(event);
});
Clicking a button should return 10 images (still gifs) related to that word.
The console.log runs on click, but it is console logging an array of 10 for all 13 words as opposed to one array for the word clicked on.
response is an Object.
response.length is an undefined.
response.data is an Array.
If you want image also, Then you should append killerImg also.
var killersGifs = {
killerSearches: ["Freddy", "Jason", "Pennywise", "Ghost Face", "American Mary", "Chucky", "Bride of Chucky", "Candyman", "Cujo", "Hannibal", "Leatherface", "Michael Meyers", "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(event) {
for (var i = 0; i < killersGifs.killerSearches.length - 1; i++) {
//console.log(this.killerSearches[i]);
//var newDiv = $("<div class='gif-div'>");
var queryURL = "https://api.giphy.com/v1/gifs/search?api_key=B26sstJns2pZuNT5HiJpqS5FV8Su1sDd&q=" + killer + "&limit=10"
var killer = killersGifs.killerSearches[i];
//console.log(queryURL);
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
// console.log(response.data.length);
for (var x = 0; x < response.data.length - 1; x++) {
var respData = response.data[x];
var image = respData.images.fixed_height_small_still.url;
var rating = respData.rating;
var dynDiv = $("<div class='dyn-div'></div>");
var killerImg = $("<img>");
killerImg.attr("src", image);
killerImg.attr("alt", "Serial Killer still frame of gif");
dynDiv.append("Rating: " + rating);
dynDiv.append(image);
$("#append-img-div").prepend($(dynDiv).append($(killerImg)));
};
});
};
},
userPush: function() {
var userInput = $("input[type='text']").val().trim();
console.log(userInput);
killersGifs.killerSearches.push(userInput);
console.log(killersGifs.killerSearches);
}
};
killersGifs.buttonLoop();
$("#killer-add-submit").on("click", function(event) {
event.preventDefault();
killersGifs.userPush();
});
$(document).on("click", "button.dynGen", function(event) {
event.preventDefault();
$("#append-img-div").empty();
killersGifs.divLoop(event);
});
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<div id="buttons"></div>
<form id="killer-form">
<label for="killer-input">Add a serial killer:</label>
<input type="text" id="killer-input"><br>
<input id="killer-add-submit" type="submit" value="Submit">
</form>
<div id="append-img-div"></div>
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.
I've created an extension and I want it to list all of the downloads in the user's downloads folder on a page rather than just opening the download folder.
This is my code:
window.onload = function(){
var maxNumOfEntries = 100;
for(i = 0; i < maxNumOfEntries; i++){
para = document.createElement('p');
para.setAttribute("id", ("download" + i));
var node = document.createTextNode("");
para.appendChild(node);
var element = document.getElementById("content");
var child = document.getElementById("stuff");
element.insertBefore(para,child);
}
var num = 0;
var currentTime = new Date().getTime();
chrome.downloads.search({text: '', limit: 100}, function(data) {
data.forEach(function(DownloadItem) {
document.getElementById('download' + num).innerHTML = DownloadItem.filename;
num++;
});
});
}
I've tried various other methods but I just can't seem to get the downloads to appear, any advice?
The text property should not be there, which is causing the problem.
chrome.downloads.search({limit: 100}, function(data) {
data.forEach(function(item, i) {
document.getElementById('download' + i).innerHTML = item.filename;
});
});
I'm creating a tool which generates a bunch of divs based on data I input into an array, however they all have the same class. The idea is that when one link is clicked it shows one of the ".catbox" divs and hides the rest.
All of these divs have the same class so I need to iterate through them, but I'm not quite sure how this is done with jQuery. Currently clicking on the last ".list" class triggers the on click event instead of all of them, and currently it shows all of the divs with the class ".catbox" instead of the corresponding one.
Here is the code:
var HTMLcatName = '<h1>%data%</h1>';
var HTMLcatImage = '<img id="cat" src="%data%">';
var HTMLcatCounter = '<p class="counter">Number of clicks: %data%</p>';
var HTMLcatList = '<p>%data%</p>'
var noCats = 'No cats selected m8';
var getCounterClass = document.getElementsByClassName("counter");
$(document).ready(function() {
cats.display();
$('.catbox').hide();
for (u = 0; u < cats.name.length; u++) {
formattedCatList = HTMLcatList.replace("%data%", cats.name[u]);
var listDiv = document.createElement('div');
listDiv.innerHTML = formattedCatList;
listDiv.className = "list";
$(".list").click(function() {
$(".catbox").toggle("slow");
});
$("body").prepend(listDiv);
}
});
var update = function() {
for (j = 0; j < getCounterClass.length; j++) {
getCounterClass[j].innerHTML = 'Number of clicks: ' + cats.clicks[j];
}
}
var cats = {
"name": ["Monte", "Jib"],
"image": ["images/monte.jpg", "images/jib.jpg"],
"clicks": [0, 0],
display: function () {
for (i = 0; i < cats.image.length; i++) {
formattedCatNames = HTMLcatName.replace("%data%", cats.name[i]);
formattedCatImages = HTMLcatImage.replace("%data%", cats.image[i]);
formattedCatCounter = HTMLcatCounter.replace("%data%", cats.clicks[i]);
var catDiv = document.createElement('div');
catDiv.className = "catbox";
catDiv.innerHTML = formattedCatNames + formattedCatImages + formattedCatCounter;
catDiv.querySelector('img').addEventListener('click', (function(catCountUp) {
return function() {
cats.clicks[catCountUp]++;
update();
};
})(i));
document.body.appendChild(catDiv);
}
},
}
The function I need help with is found within $(document).ready(function() {
Any help would be greatly appreciated.
The following can do it:
$(".list").on("click", function(){
$(this).find(".catbox").toggle("slow");
});
With $('.list') you get a group of elements of class list, so if you use $('.list').click(); you will bind the click event to just one element. You should use:
$(".list").each(function(){
$(this).click(function() {
$(".catbox").toggle("slow");
});
});
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]);
}