In javascript only, no librairies, I am trying to create a carousel.
I have 2 items:
One div for the main image and the caption (the images and captions are loaded dynamically one by one after a setTimeOut)
Another one with a list of thumbnails. I'd like to upon clicking on a thumbnail display the right image and caption.
Here is the html:
<div class="slide">
<h2 id="description" class="title">La Slide #0</h2>
<img id="largeImg" class="car" src="images/0.jpg" width="658" height="267" alt="" />
</div>
<ul id="thumbs">
</ul>
and here are my functions:
// Function to display the images and the captions switching from one to the other
function slideshowAuto() {
document.querySelector('div.slide').id = 'slide-' + i;
var caption = document.getElementById("description");
caption.innerHTML = data.slides[i].slide_name;
var img= document.getElementById("largeImg");
img.src = data.slides[i].image_src;
if (i < totalSlides) {
i++;
} else {
i = 0;
}
setTimeout("slideshowAuto()",3000);
}
// Function to display the images and the captions swaping from one to the other
function swapSlide() {
document.querySelector('div.slide').id = 'slide-' + i; // add an id on the current slide
var caption = document.getElementById("description");
caption.innerHTML = data.slides[i].slide_name;
var img = document.getElementById("largeImg");
img.src = data.slides[i].image_src;
if (i < totalSlides) {
i++;
} else {
i = 0;
}
setTimeout("swapSlide()",50);
}
// Function to display all the thumbnails
function displayAllThumbs() {
thumbs = document.getElementById('thumbs');
html = '';
for( i=0 ; i < totalSlides; i++) {
html += '<li><a onclick="swapSlide(slide-' + i + ')"><img src="' + data.slides[i].thumbnail_src + '" alt="' + data.slides[i].slide_name + '" title="' + data.slides[i].slide_name + '" /></a></li>';
}
thumbs.innerHTML = html;
}
My troubles:
The slide content display the last variables instead of the first one.
The clic on the thumbnails don't swap the "slide" content.
Here is a link of where I'm at...
Anyone can help me with that?
First,you used the global i which is changed to 7 by function preload and rechanged by function displayAllThumbs,So you got trouble 1.
Scond,you click function is swapSlide(slide-' + i + '),the parameter is a variable that doesn't exsits,also your swapSlide doesn't accept parameter.
Change to this will solve your problem:
function preload(images) {
if (document.images) {
var imageArray = data.slides[i].image_src;
var imageObjs = [];
var imageObj = new Image();
for(var j=0; j <= totalSlides - 1;j ++) {
imageObj.src = imageArray[j];
imageObjs.push(imageObj);
}
}
}
// Function to display the images and the captions switching from one to the other
function slideshowAuto() {
setSlide(i);
if (i < totalSlides) {
i++;
} else {
i = 0;
}
//document.getElementById('slide').style.webkitTransition = 'opacity 1s';
setTimeout("slideshowAuto()",3000);
}
// Function to display the images and the captions swaping from one to the other
function swapSlide(index) {
i=index; //change the current i
setSlide(index);
}
// Function to display all the thumbnails
function displayAllThumbs() {
thumbs = document.getElementById('thumbs');
html = '';
for( var k=0 ; k < totalSlides; k++) {
html += '<li><a onclick="swapSlide(' + k + ')"><img src="' + data.slides[k].thumbnail_src + '" alt="' + data.slides[k].slide_name + '" title="' + data.slides[k].slide_name + '" /></a></li>';
}
thumbs.innerHTML = html;
}
function setSlide(index){
document.querySelector('div.slide').id = 'slide-' +index; // add an id on the current slide
var caption = document.getElementById("description");
caption.innerHTML = data.slides[index].slide_name;
var img = document.getElementById("largeImg");
img.src = data.slides[index].image_src;
}
And can i get accepted?
I add a new function to avoid the repeat.
Related
I have this variables:
var imagesCount = 3;
var imageUrl = "http://www.example.com/";
var imageId = "000-000-000";
and I need to get a list like this:
<img src="http://www.example.com/GetImage.aspx?cid=000-000-000&num=1" />
<img src="http://www.example.com/GetImage.aspx?cid=000-000-000&num=2" />
<img src="http://www.example.com/GetImage.aspx?cid=000-000-000&num=3" />
Any help please.
Here implementation on JS, without jQuery.
var imagesCount = 3,
imageUrl = "http://www.example.com/GetImage.aspx?cid=",
imageId = "000-000-000",
fragment = document.createDocumentFragment(),
i,
image;
for (i = 1; i <= imagesCount; i++) {
image = document.createElement('img');
image.setAttribute('src', imageUrl + imageId + '&num=' + i);
fragment.appendChild(image);
}
document.getElementById('images').appendChild(fragment)
<div id="images"></div>
for (i = 1; i <= imagesCount; i++) {
document.writeln(imageUrl + "GetImage.aspx?cid=" + imageId + "&num=" + i + " />");
}
Just use this JS
for (var i=1; i <= imagesCount; i++){
var img = "<img src='http: //www.example. com/GetImage.aspx?cid=000-000-000&num="+ i +" />";
$(".yourContainerClass").append(img) ;
}
Must have jquery for this to work
I'm not sure whether I get your question right, but shouldn't the following work?
for(var i=1 ; i <= imagesCount; i++){
var img = $('<img />');
img.attr('src', imageUrl + "GetImage.aspx?cid=" + imageId + "&num=" + i);
img.appendTo('#imagediv');
}
I made this website quite a while ago for the purpose of grabbing random puu.sh images and displaying them. Also a warning, the content this site shows is user generated, and I can not guarantee it is SFW.
https://dl.dropboxusercontent.com/s/dlb1uke5udz8kwy/index.html
I just started looking at it again, and it appears it has some serious bugs with the systems it uses to gather content. How can I change my javascript so that it doesn't spam out puu.sh, and make it refuse connections?
Here is the code:
var currentThumb = 0;
function getImgUrl()
{
var text = (Math.round(Math.random() * 9)).toString();
//var text = '3T';
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0; i < 4; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return 'http://puu.sh/' + text;
}
function open_in_new_tab(url)
{
var win=window.open(url, '_blank');
win.focus();
}
function getImages()
{
//var width = window.innerWidth;
var images = 10;
for(var i = 0;i < images;i++)
{
var url = getImgUrl();
document.getElementById('thumbs').innerHTML += '<img class="thumb" id="thumb' + i + '" src=' + url + '>';
if(i == 0)
{
document.getElementById('fullimage').innerHTML = '<img id="big" src=' + url + '>';
$('#thumb' + currentThumb).css('border','2px solid white');
}
}
}
function refreshImages()
{
var images = 10;
for(var i = 0;i < images;i++)
{
var url = getImgUrl();
$('#thumb' + i).attr('src',url);
}
$('img').css('border','');
$('#thumb' + currentThumb).css('border','2px solid white');
}
function resize()
{
var width = $(window).width();
var height = $(window).height();
$('#fullimage img').css('max-width',width);
$('#fullimage img').css('max-height',height - 87);
}
function setBig()
{
$('#big').attr('src',($('#thumb' + currentThumb).attr('src')));
$('img').css('border','');
$('#thumb' + currentThumb).css('border','2px solid white');
resize();
}
getImages();
$('img').error(function() {
$(this).attr('src',getImgUrl());
setBig();
});
$('#thumbs img').click(function() {
$('#fullimage').html('<img id="big" src=' + $(this).attr('src') + '>');
currentThumb = parseInt($(this).attr("id").match(/\d+/));
$('img').css('border','');
$(this).css('border','2px solid white');
resize();
});
$('#fullimage').click(function() {
open_in_new_tab($('#fullimage img').attr('src'));
});
$(window).resize(function() {
resize();
});
$(document).ready(function() {
resize();
});
The problem most likely lies in
$('img').error(function() {
$(this).attr('src',getImgUrl());
setBig();
});
Your main problem seems to be that you are spamming the servers when you hit a 404 because of the error handler. Try something like
$('img').error(function() {
var _this = this;
setTimeout(function () {
$(_this).attr('src',getImgUrl());
setBig();
}, 500); // Whatever timeout is good not to spam
});
Untested, but try this new getImages() function (replace the old one)
function getImages(images)
{
if (!images) {
document.getElementById('fullimage').innerHTML = '<img id="big" src=' + url + '>';
$('#thumb' + currentThumb).css('border','2px solid white');
images = 1;
}
document.getElementById('thumbs').innerHTML += '<img class="thumb" id="thumb' + i + '" src=' + url + '>';
images++;
if (images < 10) {
setTimeout(function() { getImages(images); }, 25);
}
}
It will be called 9 times, but the first time it should do what you were doing at i = 0 and 1; It will be fired every 25ms regardless of whether images have loaded yet or not. Increase that number (25) to slow it down.
Hello, is there any way when my script outputs an image can i make it output a bootstrap row instead? I need 3 rows and 4 columns in each:
<div class="row">
<div class="col-md-3">
// IMAGE HERE
</div>
<div class="col-md-3">
// IMAGE HERE
</div>
<div class="col-md-3">
// IMAGE HERE
</div>
</div>
I need there to be 4 rows holding 3 images per row which I am struggling to get my head around. Here is my javascript code so far, if anyone could help it would be appreciated.
function displayContent() {
document.getElementById("findCar").onsubmit = function() {
var registration = document.getElementById("regPlate").value,
reference = document.getElementById("stockRef").value;
var regArray = registration.split(''),
refArray = reference.split(''),
referenceNinth = refArray[10];
var reverseReg = regArray.reverse();
var obfuscated = [];
var obf_index = 0;
for(i=0; i<=6; i++) {
obfuscated[obf_index] = refArray[i];
obf_index++;
obfuscated[obf_index] = reverseReg[i];
obf_index++;
}
obfuscated.push(referenceNinth);
var obfuscatedString = obfuscated.join("");
var camera = [];
var cameraSize = "350";
var cam_index = 0;
for(i=0; i<=1; i++) {
if(i>0) cameraSize = "800";
camera[cam_index++] = cameraSize+"/f";
camera[cam_index++] = cameraSize+"/i";
camera[cam_index++] = cameraSize+"/6";
camera[cam_index++] = cameraSize+"/5";
camera[cam_index++] = cameraSize+"/4";
camera[cam_index++] = cameraSize+"/r";
}
for (i = 0; i <= 11; i++) {
var img = new Image();
img.src = "http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i];
document.body.appendChild(img);
}
return false;
};
}
You could build up an html string in your loop and then append using .innerHTML.
e.g. - replace your final for loop with something like:
var newHtml = '<div class="row">';
for (i = 0; i <= 11; i++) {
newHtml = newHtml + '<div class="col-md-3">' +
'<img src = "' +
'http://imagecache.arnoldclark.com/imageserver/' + obfuscatedString + '/' + camera[i] + '"></img>' +
'</div>';
}
newHtml = newHtml + '</div>';
document.getElementById("#IdOfElementToAppendTo").innerHTML = newHtml;
For my project I use the OwlCarousel. http://www.owlgraphic.com/owlcarousel/#more-demos
I managed to get 3 carousels on my page. But I think the page is getting to slow. Is there a possibility that I make to many steps?
Actually I don't need to read the json file because I store it in the localStorage one page before. But I didn't know how to delete it out without corrupting the code.
So the main question is how to make just one jQuery call to fill all 3 carousels?
This is the code I use to call the carousel:
<div id="dodatni1" style="visibility:hidden" >
<div id="owl-demo" class="owl-carousel" ></div>
</div>
<div id="dodatni2" style="visibility:hidden" >
<div id="owl-demo2" class="owl-carousel" ></div>
</div>
<div id="dodatni3" style="visibility:hidden" >
<div id="owl-demo3" class="owl-carousel" ></div>
</div>
And this is the carousel code:
$(document).ready(function() {
$("#owl-demo").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg ="http://www.spleticna.si/images/"+localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 3239){
content += "<a href=\"produkt.html?id=" + j + "&slider=a\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo").html(content);
}
});
$(document).ready(function() {
$("#owl-demo2").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg = "http://www.spleticna.si/images/" + localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 2615){
content += "<a href=\"produkt.html?id=" + j + "&slider=b\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo2").html(content);
}
});
$(document).ready(function() {
$("#owl-demo3").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg = "http://www.spleticna.si/images/" + localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 3140){
content += "<a href=\"produkt.html?id=" + j + "&slider=c\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo3").html(content);
}
});
I'm not sure how much speed you could get but you can rewrite your JS:
$(document).ready(function(){
//Assuming they all use the same data source/settings?
$("#owl-demo3,#owl-demo2,#owl-demo1").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg = "http://www.spleticna.si/images/" + localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 3140){
content += "<a href=\"produkt.html?id=" + j + "&slider=c\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo3").html(content);
}
});
Am trying to write using document.write() an image at the time from my array. However it does not display any...
// *** Temporal variables
var i = 0;
var j = 0;
var x = 0;
// Create basic linear array
var ImgArray = []
// Do the 2D array for each or the linear array slots
for (i=0; i < 4 ; i++) {
ImgArray[i] = []
}
// Load the images
x = 0;
for(i=0; i < 4 ; i++) {
for(j=0; j < 4 ; j++) {
ImgArray[i][j] = new Image();
ImgArray[i][j] = "Images/" + x + ".jpg";
document.write("<img id= " + x + " img src=ImgArray[i][j] width='120' height='120'/>");
x = x + 1;
}
document.write("<br>");
}
What am I doing wrong?
Looks like your JavaScript isn't quite right...
document.write('<img id="' + x + '" src="' + ImgArray[i][j] + '" width="120" height="120"/>');
It looks like you're trying to do image preloading by using new Image(), but then you immediately write out an image element with the same src using document.write(), so the image will not have preloaded and you get no benefit. I also suspect you're missing a .src on one line in the inner loop:
ImgArray[i][j].src = "Images/" + x + ".jpg";
This looping to create image elements would be best done server-side when generating the HTML, but assuming that's not an option, you could lose the ImgArray variable completely:
x = 0;
for(i=0; i < 4; i++) {
for(j=0; j < 4; j++) {
document.write("<img id='" + x + "' src='Images/" + x + ".jpg' width='120' height='120'>");
x = x + 1;
}
document.write("<br>");
}
document.write writes any input the the location of script element. Try this instead:
in body
<div id="imageContainer"></div>
in your script, gather all output to a variable, say contentVariable, and then
document.getElementById("imageContainer").innerHTML = contentVariable;
note:
It's bad practice to use document.write and even innertml for appending elements to dom. use document.createElement and element.appendChild for dom manupilation.