Adding random number of images inside div - javascript

I have a <div> and i want to add images into it. The number of images will vary randomly.
here is what i am trying to do
$(document).ready(function () {
var img = document.getElementById("img");
$('#button').click(function () {
var randomnumber = Math.floor(Math.random() * 11) + 1;
for (var i = 1; i < = randomnumber; i++) {
$(this).append(img);
}
});
});
But it is not working. Please help
here is my code JSFiddle

You should probably use clone as simon suggests, or you can create new images:
function getImage(){
var img = new Image();
img.src = "http://cdn.acidcow.com/pics/20110830/lolcats_ever_13.jpg"
img.width = 200;
return img;
}
var rand = Math.floor(Math.random() * 11) + 1,
imgContainer = $("#imgContainer"),
i;
$("#imgNo").text(rand);
for (i=0; i<rand; i++){
imgContainer.append(getImage());
}
fiddle

uhm, you aren't defining any new images. I am not sure from where you are getting your images. If you have differeny images, you can use the next loop. Besides that, the this points to the #button element. Not sure which item it is, but if it's an input button, then it won't work. you have to use a div or article or section ... as target.
$(document).ready(function () {
$('#button').click(function () {
// random number
var randomnumber = Math.floor(Math.random() * 11) + 1;
// insert images
for (var i = 1; i < = randomnumber; i++) {
// create a new img - element
var img = document.createElement('img');
// give it an id
img.attr("id","img_" + i);
// source, link
img.attr("src","your_URL_here");
// put newly created image in the div with id yourDivIdHere
$('#yourDivIdHere').append(img);
}
});
});
the id has to be unique, that's why i'm using the index of the for loop for the id of the newly created element. Having same id for multiple HTML elements can lead to issues.
#yourDivIdHere means the div with the id yourDivIdHere, like
<div id="yourDivIdHere"></div>
When you are re-using the button, simply clear the content by using $('#yourDivIdHere').empty() method if you don't want to see that old images are still there after clicking on the button.

You need to clone the image:
$(this).append( $(img).clone() );
Your way always puts the same image (only one instance!) inside of div random amount of times. So in the end it is only one image.
If you clone it every time then you will have N amount of images

You are getting elements by id, so appended element is always the same element with id="img". Read about jQuery find() to find all elements.

Related

Javascript gallery, adding images with "for" loop

I'm creating gallery in my project, but i don't want to spam clear html and repeat it 20 times in my code. I want to create loop in javascript to get the numbers of images from my folder and later add this into one div. I've created code but i don't know how to step it.
Code:
function addingImages() {
for (var i = 0; i <= ***; i++) {
var image = document.createElement("img");
image.setAttribute("src", "images/1.jpg");
document.querySelector(".gallery").appendChild(image);
}
}
*** - i don't know what should be there. and i know i need variable to increment later numbers of images like 1.jpg , 2.jpg, 3.jpg etc.
You need to loop from 1 to 20, so set loop count to 20. Then use index from loop in setAttribute function like this:
function addingImages() {
for (var i = 1; i <= 20; i++) {
var image = document.createElement("img");
image.setAttribute("src", "images/" + i + ".jpg");
document.querySelector(".gallery").appendChild(image);
}
}
With Jquery, you can also use this:
function addImages(img_count) {
var images='';
for (var i = 1; i <= img_count; i++) {
image = '<img src="images/'+i+'.jpg">';
}
$(".gallery").html(image);
}
You need to add this jquery(Ajax) function Instead of for loop because you need to check images inside your folder before include it in the gallery
$.ajax({
url: "images/",
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("gallery").append("");
});
}
});

Event listener fails to attach or remove in some contexts

I've created a script that attaches an event listener to a collection of pictures by default. When the elements are clicked, the listener swaps out for another event that changes the image source and pushes the id of the element to an array, and that reverses if you click on the swapped image (the source changes back and the last element in the array is removed). There is a button to "clear" all of the images by setting the default source and resetting the event listener, but it doesn't fire reliably and sometimes fires with a delay, causing only the last element in a series to be collected.
TL;DR: An event fires very unreliably for no discernible reason, and I'd love to know why this is happening and how I should fix it. The JSFiddle and published version are available below.
I've uploaded the current version here, and you can trip the error by selecting multiple tables, pressing "Cancel", and selecting those buttons again. Normally the error starts on the second or third pass.
I've also got a fiddle.
The layout will be a bit wacky on desktops and laptops since it was designed for phone screens, but you'll be able to see the issue and inspect the code so that shouldn't be a problem.
Code blocks:
Unset all the selected tables:
function tableClear() {
//alert(document.getElementsByClassName('eatPlace')[tableResEnum].src);
//numResTables = document.getElementsByClassName('eatPlace').src.length;
tableArrayLength = tableArray.length - 1;
for (tableResEnum = 0; tableResEnum <= tableArrayLength; tableResEnum += 1) {
tableSrces = tableArray[tableResEnum].src;
//alert(tableSrcTapped);
if (tableSrces === tableSrcTapped) {
tableArray[tableResEnum].removeEventListener('click', tableUntap);
tableArray[tableResEnum].addEventListener('click', tableTap);
tableArray[tableResEnum].src = window.location + 'resources/tableBase.svg';
} /*else if () {
}*/
}
resTableArray.splice(0, resTableArray.length);
}
Set/Unset a particular table:
tableUntap = function () {
$(this).unbind('click', tableUntap);
$(this).bind('click', tableTap);
this.setAttribute('src', 'resources/tableBase.svg');
resTableArray.shift(this);
};
tableTap = function () {
$(this).unbind('click', tableTap);
$(this).bind('click', tableUntap);
this.setAttribute('src', 'resources/tableTapped.svg');
resTableArray.push($(this).attr('id'));
};
Convert the elements within the 'eatPlace' class to an array:
$('.eatPlace').bind('click', tableTap);
tableList = document.getElementsByClassName('eatPlace');
tableArray = Array.prototype.slice.call(tableList);
Table instantiation:
for (tableEnum = 1; tableEnum <= tableNum; tableEnum += 1) {
tableImg = document.createElement('IMG');
tableImg.setAttribute('src', 'resources/tableBase.svg');
tableImg.setAttribute('id', 'table' + tableEnum);
tableImg.setAttribute('class', 'eatPlace');
tableImg.setAttribute('width', '15%');
tableImg.setAttribute('height', '15%');
$('#tableBox').append(tableImg, tableEnum);
if (tableEnum % 4 === 0) {
$('#tableBox').append("\n");
}
if (tableEnum === tableNum) {
$('#tableBox').append("<div id='subbles' class='ajaxButton'>Next</div>");
$('#tableBox').append("<div id='cazzles' class='ajaxButton'>Cancel</div>");
}
}
First mistake is in tapping and untapping tables.
When you push a Table to your array, your pushing its ID.
resTableArray.push($(this).attr('id'));
It will add id's of elements, depending on the order of user clicking the tables.
While untapping its always removing the first table.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
resTableArray.shift(this);
So, when user clicks tables 1, 2, 3. And unclicks 3, the shift will remove table 1.
Lets fix this by removing untapped table
tableUntap = function () {
$(this).unbind('click', tableUntap);
$(this).bind('click', tableTap);
this.setAttribute('src', 'http://imgur.com/a7J8OJ5.png');
var elementID = $(this).attr('id');
var elementIndex = resTableArray.indexOf(elementID);
resTableArray.splice(elementIndex, 1);
};
So you were missing some tables after untapping.
Well lets fix tableClear,
You have a array with tapped tables, but you are searching in main array.
function tableClear() {
tableLen = resTableArray.length;
for (var i = 0; i < tableLen; i++) {
var idString = "#" + resTableArray[i];
var $element = $(idString);
$element.unbind('click', tableUntap);
$element.bind('click', tableTap);
$element.attr("src", 'http://imgur.com/a7J8OJ5.png');
}
resTableArray = [];
}
Im searching only tapped tables, and then just untap them and remove handlers.
fiddle: http://jsfiddle.net/r9ewnxzs/
Your mistake was to wrongly remove at untapping elements.

how to remove images and span dynamcially?

I am uploading images with span text dynamically inside a div.after this trying to remove specific uploaded images with its span text using below code,
var images = document.getElementsByClassName('imgclass');
for (var j = 0, leng = images.length; j < leng; j++) {
images[j].onclick = RemoveImage;
}
function RemoveImage() {
alert("here");
// var imagename = $(this).attr("src");
// alert(imagename);
$(this).remove();
$(this).find('span').remove();
//$(this).siblings().remove();
var factor = 2;
}
my problem is, the image removing fine but the span which is under that image not removing.
Here is my problem : http://jsfiddle.net/Manivasagam/72cr4bvk/39/
tell me how to solve this fix?
As you are adding img and span to a new created div, you can delete the whole div:
$(this).closest('div').remove();
JSFiddle Demo.
You add span with class "insidespan", so you may remove
$('.insidespan').remove();

Append child element to all SVG nodes with the same class

I have the following code which generates some random images on an SVG canvas.
What I want to do is use the code under the //this bit// comment to append an animate node to all the elements with a specific class.
However, the code below does not work... and for the life of me I cant figure out why, could anyone point me in the right direction
function createBackground(){
var loopLimit = Math.floor((Math.random()*100)+1);
for(var i=0; i<100; i++)
{
var jpgSelecter = Math.floor((Math.random()*10)+1);
var thisItem = document.createElementNS( svgNS, "image" );
thisItem.setAttributeNS(null,"id","node_" + Math.round(new Date().getTime() / 1000));
thisItem.setAttributeNS(null,"class","node" + jpgSelecter);
thisItem.setAttributeNS(null,"x",(Math.random()*500)+1);
thisItem.setAttributeNS(null,"y",(Math.random()*500)+1);
thisItem.setAttributeNS(null,"width",(Math.random()*500)+1);
thisItem.setAttributeNS(null,"height",(Math.random()*500)+1);
thisItem.setAttributeNS(xlinkns,"xlink:href","images/blobs" + jpgselecter + ".png");
document.getElementById("SVGcanvas").appendChild(thisItem);
}
//This Bit//
var animate = document.createElementNS( svgNS, "animateTransform" );
ani.setAttributeNS(null,"name","transform");
ani.setAttributeNS(null,"begin","0");
ani.setAttributeNS(null,"type","rotate");
ani.setAttributeNS(null,"from", "0 180 50");
ani.setAttributeNS(null,"to","360 180 50");
ani.setAttributeNS(null,"dur","4");
ani.setAttributeNS(null,"repeatCount","indefinite");
var tenner = document.getElementsByClassName("node_10");
for(i=0; i<tenner.length; i++)
{
alert(tenner[i]);
tenner[i].appendChild(ani);
}
}
Update
I've edited my code, this doesn't throw up any errors however the animation node doesn't get appended.
I see two problems:
You create an animate element, but then attempt to set attributes on an ani object and append this object to all classed elements.
Even if you change animate to ani, you cannot append the same element to multiple children. Your loop will place the element on the first found class, and then move it to the second found class, and so on. Instead, you need to create a copy of it for each item. So, either do this:
for(var i=0; i<tenner.length; i++){
var ani = document.createElementNS(svgNS,'animateTransform');
// set all attributes
tenner[i].appendChild(ani);
}
…or do this:
var ani = document.createElementNS(svgNS,'animateTransform');
// set all attributes
for(i=0; i<tenner.length; i++){
tenner[i].appendChild(ani.cloneNode(true));
}

Variables within function is null

I have the following function:
function slideDown() {
//get the element to slide
sliding = document.getElementById('slideDiv1');
//add 1px to the height each time
sliding.style.height = parseInt(sliding.style.height)+1+'px';
t = setTimeout(slideDown,30);
if (sliding.style.height == "401px") {
clearTimeout(t);
}
}
which is called within this function:
function addDiv(nextImageSlide) {
//finds the src attribute of the image nested in the Li
elemChild = nextImageSlide.firstChild;
imageSrc = elemChild.getAttribute('src');
//loops and creates six divs which will be the slices. adds background property etc
for (i = 0, j = 0, k = 1; i< = 19; i++, j++, k++) {
var newDiv = document.createElement('div');
newDiv.setAttribute('class', 'new-div');
newDiv.id='slideDiv' + k;
newDiv.style.height = '1px';
newDiv.style.background = 'url(' + imageSrc +') scroll no-repeat - '+39.5 * j + 'px 0';
var a = document.getElementById('content');
a.appendChild(newDiv);
}
slideDown();
}
Which is called within another function that defines nextImageSlide. It later removes all the divs that it just made.
The idea is for an image gallery. When the user hits the next button, I want slices of the next image to slide down to show the next image. Those slices are then taken away and the new image revealed.
I would like something like this: http://workshop.rs/projects/jqfancytransitions/.
It's for an assignment so we have to write all the code ourself and this is the best way I can think to replicate it. The only problem is that I keep getting an error:
'sliding is null. sliding.style.height = parseInt(sliding.style.height)+1+'px';'
No matter what I do I can't get rid of it. The thing is if I define sliding as a totally different id, (for example I made a random little div outside of everything), it working.
This error shows when I try to access the divs, it just made that it throws a hissy fit.
Anyone see any errors in my code?
Hopefully this is just a typo while pasting into the site here, but:
car a = document.getElementById('content');
^---syntax error, which'll kill your entire script - var?

Categories