How do I change the image src in my slider? - javascript

I have this image for a slider. I want it to fade to the next image after the button is clicked. The JQuery makes the image fade in and out to make the transition cleaner when the src changes. However, the image stays the same after fading.
Html
<button onclick = "prev()" id = "prev">Prev</button>
<img id = "slider" src = "" height = "600px" width = "600px"/>
<button onclick = "next()" id = "next">Next</button>
JQuery
var images = ['', '', ''];
var num = 0;
function next() {
var slider = $('#slider');
num++;
if(num >= images.length) {
num = 0;
}
slider.fadeOut('slow', function() {
slider.src = images[num];
slider.fadeIn('slow');
});
}
function prev() {
var slider = $('#slider');
num--;
if(num < 0) {
num = images.length-1;
}
slider.fadeOut('slow', function() {
slider.src = images[num];
slider.fadeIn('slow');
});
}
I have taken out the images I tested it with as their links were too long. The three slider images would be in the JQuery "images" variable and the starting one in the image src.

Assuming that images is an array of image URLs, then your mistake is trying to set slider.src instead of slider.attr('src, value);.
So, use this instead:
slider.attr('src', images[num]);

Related

how to change the picture on a page without a button or without hovering over it

I have to make a program which is able to present an animation once opened.
Here the code that I have so far, but I am not sure how to fix it to automatically show the pictures and I am not allowed to use a button or hover over the image to change it , and I'm not allowed to use a premade gif or a gif at all
var index = 0;
var ImageList = ["http://www.iconsplace.com/icons/preview/orange/happy-256.png", "http://www.iconsplace.com/icons/preview/orange/sad-256.png"];
var image1 = document.getElementById("myImage");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if (timerValue >= 30) {
img.src("http://www.iconsplace.com/icons/preview/orange/happy-256.png");
} else if (timer <= 60) {
img.src("http://www.iconsplace.com/icons/preview/orange/sad-256.png");
} else {
img.src("http://www.iconsplace.com/icons/preview/orange/happy-256.png");
}
}
<img id="myImage" src="http://www.iconsplace.com/icons/preview/orange/happy-256.png" style="width:200px">
You can use an interval:
window.onload = function(){
var index = 0;
var ImageList = ["Images/happy.png", "Images/sad.png"];
var image1 = document.getElementById("myImage");
var a = 0;
setInterval(function(){
a++;
image1.src = ImageList[a % ImageList.length];
}, 30000);
}
It changes the image per 30 seconds.
You have the two images in an array. USE it!
var index = 0;
var ImageList = ["http://www.iconsplace.com/icons/preview/orange/happy-256.png", "http://www.iconsplace.com/icons/preview/orange/sad-256.png"];
window.onload=function() { // page has finished loading, image is available
var image1 = document.getElementById("myImage");
var tId=setInterval(function() {
index=index==0?1:0; // if 0 then 1 else 0
// for more images instead use:
// index++; if (index>=ImageList.length)index=0;
image1.src=ImageList[index]; // how to set the image src
},5000); // every 5 seconds
}
<img id="myImage" src="http://www.iconsplace.com/icons/preview/orange/happy-256.png" style="width:200px">

limit javascript toggle according to select box value

Here is link of my current fiddle
jsFiddle
JS --
$('.click').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'http://imageshack.us/a/img703/8236/l6hu.png') src = 'http://imageshack.us/a/img20/1651/fibz.png';
if (origsrc == 'http://imageshack.us/a/img20/1651/fibz.png') src = 'http://imageshack.us/a/img703/8236/l6hu.png';
$(this).attr('src', src);
}
});
i am able to toggle image onclick with another image and vice versa. This is okay, but i want to limit the toggle only when green image is already selected. If i select 3 from select box then i can toggle white image into green image only 3 times, not more than 3. I also need help for another scenerio - if i select 3 from select box and toggle first 3 image and next moment i change the 2nd image into white and click 5th image to turn green then it will be possible. I am week in javascript or jquery, so need proper information about this problem. So plz help me out.
Here is a more comprehensive approach fiddle which will keep your limit in sync and handle discrepancies when the limit changes.
var quantity = 0; // will maintain limit
var stack = []; // will maintain ordered green buttons
$("#select").change(runWrapper);
function runWrapper() {
quantity = Number($("#select").val()); // set the limit
groom(); // turn off those that were turned on last
//run(); // this is your run function, uncomment
}
function groom(){
// let's test if we are over the limit
while(stack.length > quantity) {
// remove last which was set to green
$(stack.pop()).trigger("click")
// to remove the oldest/first set to green use
// $(stack.shift()).trigger("click")
}
}
$('.click').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'http://imageshack.us/a/img703/8236/l6hu.png') {
// limit reached
if(stack.length >= quantity) {
alert(quantity + " limit reached!");
return;
}
src = 'http://imageshack.us/a/img20/1651/fibz.png';
// turning green push the DOM reference to the top of the stack
stack.push(this);
}
if (origsrc == 'http://imageshack.us/a/img20/1651/fibz.png') {
src = 'http://imageshack.us/a/img703/8236/l6hu.png';
// turning white remove the DOM reference from stack
var self = this;
stack = $.grep(stack, function(val) {
return self != val;
})
console.warn(stack);
}
$(this).attr('src', src);
}
});
You can update the function like this - fiddle is here - http://jsfiddle.net/4QkM8/5/
I changed id of select box to selQty
var selectedCount = 0;
$('.click').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'http://imageshack.us/a/img703/8236/l6hu.png'){ if (selectedCount < $('#selQty').val()){src = 'http://imageshack.us/a/img20/1651/fibz.png';
selectedCount ++;
} }
if (origsrc == 'http://imageshack.us/a/img20/1651/fibz.png') {src = 'http://imageshack.us/a/img703/8236/l6hu.png';selectedCount --;}
$(this).attr('src', src == '' ? origsrc : src);
}
});
use a variable to keep track of how many items have been selected, and compare it to the quantity in the select box.
var count = 0;
var unselected_img = 'http://imageshack.us/a/img703/8236/l6hu.png';
var selected_img = 'http://imageshack.us/a/img20/1651/fibz.png';
$('.click').on({
'click': function () {
var max_allowed = parseInt($("#select").val(), 10);
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == unselected_img && count < max_allowed) {
src = selected_img;
count++;
} else if (origsrc == selected_img) {
src = unselected_img;
count--;
} else {
alert("Too many selected.");
}
if (src) {
$(this).attr('src', src);
}
}
});
DEMO

With only one button to scroll through images, how do I make a permutation?

I am writing this in JavaScript, and the issue is that I can't seem to figure out how to make a permutation. Ideally, I want to click the button and image would change to next, from a1.jpg to a2.jpg to a3.jpg to a4.jpg to a1.jpg and so on... But when I wrote this code, it would skip a2 and a3. I also did rearrange the conditionals since I realized that it reads from the top to bottom, but it would always skip one of the four pictures.
function changeImage() {
if (document.images) {
if (document["buttonOne"].src == a3.src){
document["buttonOne"].src = a4.src}
}
if (document.images) {
if (document["buttonOne"].src == a2.src){
document["buttonOne"].src = a3.src
}
if (document.images) {
if (document["buttonOne"].src == a1.src){
document["buttonOne"].src = a2.src}
}
if (document.images) {
if (document["buttonOne"].src == a4.src){
document["buttonOne"].src = a1.src}
}
}
Try it in a more simple way
var imgs = ['a1.jpg', 'a2.jpg', 'a3.jpg', 'a4.jpg'];
function changeImage() {
var img = document["buttonOne"];
if (!img._index) img._index = 0;
img.src = imgs[img._index++];
if (img._index >= imgs.length) img._index = 0;
}
img._index replaces the global variable with index of the shown image. Good to use when you want to change a few images, each of them will keep its own counter.
ps: if the only thing that changes is the number in the filename then the code can be even shorter without an array:
function changeImage(max) {
var img = document["buttonOne"];
if (!img._index) img._index = 0;
img.src = 'a' + img._index + '.jpg';
if (img._index >= max) img._index = 0;
}

jQuery swap Next/Previous image, images in array

I have a literal array of image IDs and I need to swap them in <img src=""> to Next or Previous image on buttons click events. The initial current image ID is known from the img src provided server-side on initial page load.
Obviously, before swapping, the URL needs to be constructed with the target ID like this:
'http://site.com/images/' + imageID + '.jpg'
I'm a JS/jQuery beginner and would like to learn a correct, minimalistic approach. TIA.
My code to start off:
var images=["777777","666666","555555"];
var max = $(images).length;
$('#swapnextimg').click{
$("#imageswap").attr('src', ...... );
}
<a id="swapnextimg"></a>
<a id="swapprevsimg"></a>
<div id="imagebox">
<img id="imageswap" src="http://site.com/images/123456.jpg">
</div>
Here is an example:
http://jsfiddle.net/ndFGL/
$(function() {
// Image ID array
var images = ['240', '260', '250', '123', '200'];
var max = images.length;
// Get current image src
var curSrc = $('#imageswap').attr('src');
// Find ID in image src
var curID = curSrc.replace(/.*\/(.*?)\.jpg/i, '$1');
var curIdx = 0;
// Search image list for index of current ID
while (curIdx < max) {
if (images[curIdx] == curID) {
break;
}
curIdx++;
}
// For convenience
var imgSrcBase = 'http://placehold.it/';
// Next image on button (and image) click
$('#swapnextimg,#imageswap').click( function() {
curIdx = (curIdx+1) % max;
$("#imageswap").attr('src', imgSrcBase+images[curIdx]+'.jpg');
});
// Prev image on button click
$('#swapprevsimg').click( function() {
curIdx = (curIdx+max-1) % max;
$("#imageswap").attr('src', imgSrcBase+images[curIdx]+'.jpg');
});
});
Try below code,
var images=["777777","666666","555555"];
var max = $(images).length;
var imgPtr = 0;
$('#swapnextimg').click{
if (imgPtr == max) {
//comment the below return and set imgPtr to 0 for rotating the images
return;
}
$("#imageswap").attr('src', 'http://site.com/images/' + images[imgPtr++] + '.jpg');
}
$('#swapprevsimg').click{
if (imgPtr == 0) {
//comment the below return and set imgPtr to max-1 for rotating the images
return;
}
$("#imageswap").attr('src', 'http://site.com/images/' + images[imgPtr--] + '.jpg');
}
<a id="swapnextimg"></a>
<a id="swapprevsimg"></a>
<div id="imagebox">
<img id="imageswap" src="http://site.com/images/123456.jpg">
</div>
I assume that you've got one img tag, and only one. And that the purpose of this is to change that single image tag.
To do that you will need the nex and prev button.
<div id="container">
<img src="#" data-num="" />
<span class"prev">prev</span>
<span class"next">next</span>
</div>
The object:
var obj = [0: 'dog', 1: 'cat'];
now for the next and prev to work. We are going to take a look at the .on() method.
$('.container span').on('click', function(){
var $this = $(this), // span
currentNum = $this.siblings('img').data('num'), // img data-num
nextNum = $this.is('.next') ? currentNum+1 : currentNum-1, // if class is next add 1, if not remove 1
link = "http://site.com/images/" + obj[nextNum] + ".jpg" // the link
// either it's not the last images or it returns
nextNum != obj.length() || return
$('img').attr('src', link).data('num', nextNum)
})
Hope this helped you. If not please let me know

jquery background image rotating script doesn't work

I'm writing this script to rotate a background Image every 3 seconds but it doesn't work at all and i'm stumped as to why not.
$(document).ready(function() {
var inc = 0;
var bgImages = new Array();
bgImages.push("Images/backgroundDog-small.jpg");
bgImages.push("Images/backgroundDog1-small.jpg");
bgImages.push("Images/backgroundDog2-small.jpg");
bgImages.push("Images/backgroundDog3-small.jpg");
setInterval(change, 3000);
function change() {
//if we're not at the end of the array
if (inc < (bgImages.length)) {
var image = bgImages[inc];
$('body').css('backgroundImage', image);
console.log(image);
inc++;
//reset the counter inc and go through the array again
} else {
inc = 0;
}
}
});
The background-image attribute in CSS doesn't expect just the image URL; you need to write it like you actually would in a stylesheet: url("example.png")
$('body').css('backgroundImage', 'url("'+image+'")');

Categories