I have created a "prev/next" slideshow using javascript, now I want to add a counter(1/10, 2/10, 3/10...) beside my "prev/next" buttons but nothing seemed to work.
This is my first time attempting to make a website, I know nothing about jQuery, so please stick with html+javascript if possible. Here is my script
var image = new Array(
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg",
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg")
var imgNumber=1
var numberOfImg=2
function previousImage(){
if(imgNumber>1){
imgNumber--
}
else{
imgNumber = numberOfImg
}
document.slideImage.src = image[imgNumber-1]
}
function nextImage(){
if(imgNumber < numberOfImg){
imgNumber++
}
else{
imgNumber = 1
}
document.slideImage.src = image[imgNumber-1]
}
if(document.images){
var image1 = new Image()
image1.src = "http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg"
var image2 = new Image()
image2.src = "http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg"
}
Script+html: http://jsfiddle.net/nLHY9/5/
(Prev/Next buttons seem not to be working on this----they work fine when I launched them from laptop to browser.)
you could have used some existing javascript image sliders, for example, sliderman slider, for your current code, you can do like, add an element like span, to hold the count, and you could add a function like:
function changeCounter(cur, total) {
document.getElementById("counter").innerHTML = cur + "/" + total;
}
and call it in your previousImage() and nextImage() functions, as in this demo jsfiddle
There are many pure css slideshows that are beautiful and can do impressive things. However, as you try to support older browsers, the pure css slideshows get less and less impressive or even impossible. JavaScript is the most flexible and powerful way to go. That being, I wanted to help you clean up your code. I only had a few minutes, so this is a quickly thrown together plugin, but it should get you on the right track.
First, a few notes on your code:
//you're missing semicolons everywhere. ";"
/* "var image" is very unclear.
* it's an array, so it should be plural "images"
* there aren't images in this array - it's image urls or sources
* instead of "new Array" you could just use "[]"
*/
var image = new Array(
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg",
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg")
var imgNumber=1 //the name doesn't mean anything. I have to assume that you mean "currentImgNumber" or something to that effect
var numberOfImg=2 //this could be determined by checking the length of your array - myArray.length
And here's my exampe plugin:
Live demo here (click).
/***** This section is how you use the plugin. I start writing with the usage and then I make it mean something *****/
window.onload = function() { //when the page is loaded
var fooElem = document.getElementById('foo'); //get an element where we will attach the plugin
var foo = Object.create(slideshow); //create a new slideshow object
foo.create({ //create a slideshow with the given options
element: fooElem, //the element where the slideshow will be
sources: [ //image urls
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg",
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg"
]
});
//we can make more of these and with different options
var barElem = document.getElementById('bar');
var bar = Object.create(slideshow);
bar.create({
element: barElem,
sources: [
"http://eggboss.com/wp-content/uploads/2013/09/The-Gentleman-233x300.png",
"http://fc07.deviantart.net/fs71/f/2013/040/8/a/profile_picture_by_classy_like_a_sir-d5uf426.jpg"
]
});
};
/**** now let's create the plugin and make it work as it is used above *****/
var slideshow = {
currentIndex: 0,
imgs: [],
create: function(options) {
options.element.className+= ' slideshow'; //add a class to the main element for styling
this.imgs = this.getImgs(options.sources); //make img html
var controls = this.getControls(); //make controls
//add the html to the element from the options
var frag = document.createDocumentFragment();
this.imgs.forEach(function(img) {
frag.appendChild(img);
});
frag.appendChild(controls);
options.element.appendChild(frag);
},
getImgs: function(sources) {
var imgs = [];
sources.forEach(function(src, i) {
var img = document.createElement('img');
img.src = src;
imgs.push(img);
if (i > 0) {
img.style.display = 'none'; //hide all but first image
}
});
return imgs;
},
getControls: function() {
var that = this; //so that we can access "this" within the click functions
var controls = document.createElement('div');
controls.className = 'controls';
var counter = document.createElement('span');
counter.className = 'counter';
this.setCounter(counter);
var prev = document.createElement('a');
prev.textContent = 'Prev';
prev.className = 'prev';
prev.addEventListener('click', function() {
newIndex = (that.currentIndex) ? that.currentIndex-1 : that.imgs.length-1;
that.changeImg(newIndex, counter);
});
var next = document.createElement('a');
next.textContent = 'Next';
next.className = 'next';
next.addEventListener('click', function() {
newIndex = (that.currentIndex !== that.imgs.length-1) ? that.currentIndex+1 : 0;
that.changeImg(newIndex, counter);
});
controls.appendChild(prev);
controls.appendChild(next);
controls.appendChild(counter);
return controls;
},
changeImg: function(newIndex, counter) {
this.imgs[this.currentIndex].style.display = 'none';
this.imgs[newIndex].style.display = 'inline';
this.currentIndex = newIndex;
this.setCounter(counter);
},
setCounter: function(counter) {
counter.textContent = (this.currentIndex+1)+' / '+this.imgs.length;
}
};
Related
I probably should not be attempting this, but I have gotten so far and I don't want to give up now. I want to create my own Lightbox type script. I can create an absolute div with the class ligthbox and it covers the page. Then I create a img that is fixed and it animates when loading. The I also have nav arrows to move through the photos. All works accept when I click on the arrows it creates new close X and arrows. I don't understand because the is done through the animation function which is not attached to the arrow function.
I have added event.stopPropagation(); to the arrow function and the animate function but that did not work.
The function that initiates everything.
jQuery(".marks-lightbox img").click( function() {
var Img = jQuery(this),
cImg = Img.attr("src"),
allImg = jQuery(".marks-lightbox img");
//finding the current img from the available images
for(i=0; i < allImg.length; i++) {
if( jQuery(allImg[i]).attr("src") == Img.attr("src") ) {
lbImgCurrent = i;
}
}
makeLightBox()
});
function makeLightBox() {
var bodyHeight = jQuery("body").height(),
lightbox = jQuery("<div>").addClass("lightbox").css({"width":"100vw","height":bodyHeight}),
scrollTop = 72,
lbContainer = jQuery("<div>").addClass("lbContainer"),
lbImg = jQuery(".marks-lightbox img"),
imgSRC = jQuery(lbImg[lbImgCurrent]).attr("src"),
lbClose = jQuery("<span>").addClass("lb-close").text("X");
jQuery("body").prepend(lightbox);
lbContainer.appendTo(".lightbox");
jQuery('<img src="'+ imgSRC +'">').load(function() {
jQuery(this).appendTo(".lbContainer").css("display","none").addClass("lb-image");
var w = jQuery(".lb-image").width(),
h = jQuery(".lb-image").height(),
lbw = lightbox.width(),
margin = (lbw - w) /2;
jQuery(this).appendTo(".lightbox").css({"position":"fixed","display":"block","width":0,"height": 0}).animate({"top":scrollTop,"width":w,"height":h,"margin-left":margin, "margin-right":margin},1000,function(event){
var lbimg = jQuery(this),
lbH = lbimg.height() + 63,
lbLeft = lbimg.offset().left,
lbW = lbimg.width(),
larrow = jQuery("<div><</div>").addClass("left-arrow-lb lb-arrow"),
rarrow = jQuery("<div>></div>").addClass("right-arrow-lb lb-arrow");
larrow.appendTo("body").css({"position":"fixed","top":lbH/2,"left":lbLeft+18});
rarrow.appendTo("body").css({"position":"fixed","top":lbH/2,"left":lbLeft+lbW-90});;
lbClose.appendTo(".lightbox").css({"position":"fixed","top": lbH,"left": lbLeft+lbW - 18});
});
});
}
Here is the click function
jQuery("body").on("click",".left-arrow-lb", function() {
console.log(jQuery(this));
var lbImgLength = jQuery(".marks-lightbox img").length,
lbImg = jQuery(".marks-lightbox img");
lbImgCurrent = (lbImgCurrent < 1 ) ? lbImgLength : lbImgCurrent -1;
var imgSRC = jQuery(lbImg[lbImgCurrent]).attr("src");
console.log(imgSRC);
jQuery(".lb-image").attr("src",imgSRC);
});
Every click creates a load new img scr and animates the photo (unexpectedly) and creates new arrows and close x.
I found it was the on("load"... working every time an image was being loaded. So I created a var reload and set it to true. The in the on(load... function I said if not true return false. In the arrow functions set the reload to false. This prevented the on(load... working reloading.
Js beginner here.
I have a function like this:
generateSteps: function() {
var stepsLength = this.data.steps.length;
var dataStepsInit = this.data.steps;
for (var i = 0; i < stepsLength; i++) {
var stepsItem = dataStepsInit[i].ITEM;
var arrayItem = this.animationNodes[stepsItem - 1];
var transition = this.animationParameters[i].transition;
var options = this.animationParameters[i].options;
var speed = this.animationParameters[i].speed;
var delay = this.animationParameters[i].delay;
arrayItem.delay(delay).show(transition, options, speed);
if (dataStepsInit[i].AUDIOID) {
var audioClass = dataStepsInit[i].AUDIOID;
var audioPlayer = this.template.find("audio." + audioClass);
setTimeout(playAudioOnDelay,delay);
};
var playAudioOnDelay = function() {
audioPlayer[0].pause();
audioPlayer[0].currentTime = 0;
audioPlayer[0].play();
};
}
}
What it does is generate data from JSON and display animated elements one by one on delay. Animation part work fine. I can assign required animations and delay to DOM elements and show them in right order.
But what I want to do in the same time is also to play an audio on delay (so I use setTimeout). Everything is almost fine, I play audio in right time (correct delay value) but I always play the same audio (which is last element) because audioPlayer always is the same DOM node.
I think this have something to do with this or I mixed a scope?
Try this:
generateSteps: function() {
var stepsLength = this.data.steps.length;
var dataStepsInit = this.data.steps;
for (var i = 0; i < stepsLength; i++) {
var stepsItem = dataStepsInit[i].ITEM;
var arrayItem = this.animationNodes[stepsItem - 1];
var transition = this.animationParameters[i].transition;
var options = this.animationParameters[i].options;
var speed = this.animationParameters[i].speed;
var delay = this.animationParameters[i].delay;
arrayItem.delay(delay).show(transition, options, speed);
if (dataStepsInit[i].AUDIOID) {
var audioClass = dataStepsInit[i].AUDIOID;
var audioPlayer = this.template.find("audio." + audioClass);
setTimeout(playAudioOnDelay(audioPlayer),delay);
};
}
function playAudioOnDelay(audioPlayer){
return function(){
audioPlayer[0].pause();
audioPlayer[0].currentTime = 0;
audioPlayer[0].play();
}
}
}
Essentially, your problem looks like this: http://jsfiddle.net/po0rLnwo/
The solution is : http://jsfiddle.net/gpfuo1s8/
Check the console in your browser.
I'm working on a synth-like program in the browser using web audio. This may sound stupid, but I can't seem to get the button to create the knob when it's clicked. I've tried setting up the knob in a few different ways including, adding the data- prefix to the knobs attributes, but i can't seem to get it. The way I currently have it set up is this:
$(document).ready(function()
{
var add_osc = $('li#add_osc');
var osc;
var add_dest = $('li#add_dest');
var dest;
var add_fx = $('li#add_fx');
var fx = $('.fx');
//left side menu
$('#simple-menu').sidr();
//hide sound fx in menu
$(".fx").hide();
//general purpose knob <----- **PROBLEM CODE** -----!
add_osc.click(function()
{
var input = $('document').createElement("input");
input.type = "text";
input.addClass('dial');
$(".dial").knob();
input.min = 0;
input.max = 100;
input.displayPrevious = true;
input.lineCap = "round";
input.width = 100;
input.value = 0;
$("body").append(input);
});
//toggle fx list
add_fx.click(function()
{
fx.toggle();
});
});
any help is appreciated!
You have to set the needed plugin data-attribute and than execute the plugin on the newly created and appended element.
Code:
$(document).ready(function () {
var add_osc = $('li#add_osc');
var osc;
var add_dest = $('li#add_dest');
var dest;
var add_fx = $('li#add_fx');
var fx = $('.fx');
//hide sound fx in menu
$(".fx").hide();
//general purpose knob <----- **PROBLEM CODE** -----!
add_osc.click(function () {
var $input=$("<input type='text'>")
$input.addClass('dial');
$input.attr('data-min', 0);
$input.attr('data-max', 100);
$input.attr('data-displayPrevious', true);
$input.attr('data-lineCap', 'round');
$input.attr('data-width', 100);
$input.val(0);
$("body").append($input);
$input.knob();
});
//toggle fx list
add_fx.click(function () {
fx.toggle();
});
});
Demo: http://jsfiddle.net/hD8LK/
I'm trying to make a slideshow of pictures and send them to an another window. But after selecting images and pressing the button for showing slideshows, nothing happens. I'm using firebug to detect bugs and when I'm going wrong. But I'm not getting any error from firebug so I gotta ask you guys. This is my code.
var infoBox;
var formTag;
var imgUrlList;
var imgTextList;
var windVar;
var urlList;
var textList;
function init() {
var i;
infoBox = document.getElementsByClassName("outerBox");
for (i=0; i<infoBox.length; i++) {
infoBox[i].onmouseover = showInfoBox;
infoBox[i].onmouseout = hideInfoBox;
}
formTag = document.getElementsByTagName("input");
for (i=0; i<formTag.length; i++) {
formTag[i].onclick = checkedBox;
}
windVar = null;
imgTextList = [];
imgUrlList = [];
}
window.onload = init;
function showInfoBox() {
var showInfo;
showInfo = this.getElementsByClassName("innerBox")[0];
showInfo.style.visibility = "visible";
}
function hideInfoBox() {
var hideInfo;
hideInfo = this.getElementsByClassName("innerBox")[0];
hideInfo.style.visibility = "hidden";
}
function checkedBox() {
var ImgNode, ImgTag;
for (i=0; i<formTag.length; i++) {
imgNode = this.parentNode.parentNode.firstChild;
imgTag = imgNode.nextSibling
if (this.checked) {
imgTag.className = "markedImg";
}
else {
imgTag.className = "unmarkedImg";
}
}
}
function slideShowBtn() {
var url, i, filename;
imgUrlList.length = 0;
imgTextList.length = 0;
for (i=0; i<formTag.length; i++) {
if (formTag.checked) {
url = infoBox.firstChild.getElementsByTagName("img")[i].src;
filename = infoBox.firstChild.getElementsByTagName("span")[i].src;
imgUrlList.push(url);
imgTextList.push(filename);
}
else break;
}
newWindow(700,600,"slideshow.htm");
}
function newWindow(width,height,fileName) {
var windProporties;
windProporties = "top=100, left=100,toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + width + ",height=" + height;
if (windVar != null) if (windVar.closed == false) windVar.close();
windVar = window.open(fileName,"bildspel",windProporties);
}
The formTag variabel is from a checkbox-input-tag. And it's from that I decide which pictures are selected and will be moved to the new page. ImgTextList and imgUrlList are global variables that'll also be in the next window. infoBox is a reference to a div class which is called OuterBox and inside it is an another div-class named innerBox, it's in the innerBox classdiv which the img and span-tags are. The code for the slideshow is already written and I'm just writing code for sending the variables to it.
Edit: I should have been a little more informative. But here's the code for the slideshow part where window.opener is present. And I've added all the remaining code that's above. How do you embed files?
// JavaScript for the slideshow page
// ----- Global variables -----
var imgUrlList = window.opener.imgUrlList; // Array with filenames of selected images. Initialized to an empty array.
var imgTextList = window.opener.imgTextList; // Array with image texts of selected images. Initialized to an empty array.
var slideshowMenu = null; // Reference to the image menu.
var slideshowImg = null; // Reference to the slideshow img tag.
var slideshowText = null; // Reference to the tag for the image text.
// ---- Create the image menu and show the first image. Also attach event handlers. ----
function initSlideshow() {
// Create a image list from the content of the variable imgUrlList
var HTMLcode = "<select id='imgMenu'>";
for (var i=0; i<imgTextList.length; i++) {
HTMLcode += "<option>" + imgTextList[i] + "</option>";
} // End for
HTMLcode += "</select>";
document.getElementById("iMenu").innerHTML = HTMLcode; // Add the select and option tags to the HTML code
slideshowMenu = document.getElementById("imgMenu"); // Save a reference to the menu's select tag
slideshowMenu.selectedIndex = 0; // Select the first option in the menu
slideshowImg = document.getElementById("slideshowBox").getElementsByTagName("img")[0];
slideshowText = document.getElementById("slideshowBox").getElementsByTagName("div")[0];
// Show the first image
slideshowImg.src = imgUrlList[0];
slideshowText.innerHTML = imgTextList[0];
// Attach event handlers
var slideshowButtons = document.getElementById("slideshowForm").getElementsByTagName("input");
slideshowButtons[0].onclick = showPrevImage;
slideshowButtons[1].onclick = showNextImage;
slideshowMenu.onchange = showSelectedImage;
} // End initSlideshow
window.onload = initSlideshow;
// ---- Show previous image in the list (menu) ----
function showPrevImage() {
var ix = slideshowMenu.selectedIndex; // Index for the current image
if (ix > 0) { // If it's not already the first image
slideshowMenu.selectedIndex = ix-1;
slideshowImg.src = imgUrlList[ix-1];
slideshowText.innerHTML = imgTextList[ix-1];
}
} // End showPrevImage
// ---- Show next image in the list (menu) ----
function showNextImage() {
var ix = slideshowMenu.selectedIndex; // Index for the current image
if (ix < slideshowMenu.length-1) { // If it's not already the last image
slideshowMenu.selectedIndex = ix+1;
slideshowImg.src = imgUrlList[ix+1];
slideshowText.innerHTML = imgTextList[ix+1];
}
} // End showNextImage
// ---- Show selected image in the list (menu) ----
function showSelectedImage() {
var ix = slideshowMenu.selectedIndex; // Index for the selected image
slideshowImg.src = imgUrlList[ix];
slideshowText.innerHTML = imgTextList[ix];
} // End showSelectedImage
Um, you never do anything to send it. Either pass it as a querystring parameter or have the child reference a global variable in the opener.
var foo = window.opener.imgUrlList;
I have a function that places an image provided by the input of the user into the body of an html page. When a second input is received I want to replace this picture with the new one. I have attempted to do just this in the below function.
function show_image(src, alt) {
var img = document.createElement("img");
img.src = src;
img.width = 400;
img.height = 300;
img.alt = alt;
var counter;
var mynodes= new Array();
mynodes.push(img);
counter+=1;
if(counter==1){
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
else if(counter!=1)
{
var newNode=mynodes[counter-1];
var oldNode=mynodes[counter-2];
document.body.replaceChild(newNode,oldNode);
}
The variable counter is a local variable.
Each time the method is called counter is initialized to 0.
Same thing with your mynodesvariable. It is always going to have only one node in the array.
So you may want to change your logic here. Do you want help rewriting this function?
Your code is totally awkward. As far as I can tell, you could simply change the same img tag instead of changing the whole node each time. There's barely a reason for a function..
Click here for a live demo.
function changeImg(img, src, alt) {
//I doubt you even need a function for this.
img.src = src;
img.alt = alt;
}
var img = document.createElement('img');
//you could just use a css class instead...
//that's probably better anyway...why does your js care how it looks?
img.width = 400;
img.height = 300;
document.body.appendChild(img);
changeImg(img, 'http://static.jsbin.com/images/favicon.png', 'image');
var imgSrcInput = document.getElementById('imgSrc');
var imgAltInput = document.getElementById('imgAlt');
var button = document.getElementById('change');
button.addEventListener('click', function() {
changeImg(img, imgSrcInput.value, imgAltInput.value);
});
I put together an object oriented example. This makes your logic very reusable and friendly. Check out the code in action here (click).
window.onload = function() { //usage
var someElement = document.getElementById('someIdHere');
var anotherElement = document.getElementById('anotherIdHere');
imageReplacer.setup({
element: someElement,
initSrc: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRg-icdkibfDt8VE7FkaKZyVUh8SBR4YTGd-2Jz1wZeUVacv4YD8zrvwclN',
initAlt: 'Starting Image'
});
imageReplacer.setup({
element: anotherIdHere,
initSrc: 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRrHWuOzgYPbsuSF9cYQo3ORkcdIC4-8xaszlCrI3f7arAC7vhV7HwMN_fG',
initAlt: 'Starting Image'
});
};
var imageReplacer = { //package up your app
setup : function(options) {
//create a new imageReplacer so that each one will operate independently. The "this" pointer will refer to each element's imageReplacer.
options.element.imageReplacer = Object.create(imageReplacer);
options.element.imageReplacer.makeReplacer(options);
},
makeReplacer : function(options) {
options.element.className = 'imageReplacer';
var markup = this.createMarkup();
this.changeImage(options.initSrc, options.initAlt);
this.addClick(this.button);
options.element.appendChild(markup);
},
createMarkup : function() {
var frag = document.createDocumentFragment();
this.srcInput = document.createElement('input');
this.srcInput.type = 'text';
this.srcInput.placeholder = 'Image Source';
this.altInput = document.createElement('input');
this.altInput.type = 'text';
this.altInput.placeholder = 'Image Alt';
this.button = document.createElement('button');
this.button.textContent = 'Change Image';
this.imgTag = document.createElement('img');
frag.appendChild(this.srcInput);
frag.appendChild(this.altInput);
frag.appendChild(this.button);
frag.appendChild(this.imgTag);
return frag;
},
addClick : function(button) {
var that = this;
button.addEventListener('click', function() {
that.changeImage(that.srcInput, that.altInput);
});
},
changeImage : function(src, alt) {
this.imgTag.src = src;
this.imgTag.alt = alt;
}
};
Instead of creating a function to dynamically change the picture(which did work), I decided to hide one picture on my index.html file. And then changed the src with $("#my_image").attr("src","img/fire.gif"); #my_image being the id of the image tag.