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
Related
var n=0;
var images=["FullSizeRender (1).jpg","IMG_1875.JPG","IMG_4665.JPG","IMG_5213.JPG"];
$(document).ready(function() {
// Change image
$("#himg").click(function(){
n++;
if(n==images.length){
n=0;
};
document.getElementById("himg").src=images[n];
$("#himg").find('img[src="' + images[n] + '"]').fadeOut();
$("#himg").find('img[src="' + images[n+1] + '"]').hide().fadeIn();
});
<div class="col-xs-2">
<div id="handbags">
<h4>Handbags</h4>
<img id="himg" src="FullSizeRender (1).jpg" />
</div>
</div>
I have made an array where images change on click, but I am trying to make the images fade on click instead of sharply changing. I've tried selecting the images by source using the index from the array, but it's not working.
Try this:
$(document).ready(function() {
var n = 0;
var images = ["FullSizeRender(1).jpg","IMG_1875.JPG","IMG_4665.JPG","IMG_5213.JPG"];
var image = $('#himg');
image.on('click', function() {
var newN = n+1;
if (newN >= images.length) { newN = 0 };
image.attr('src', images[n]);
image.fadeOut(300, function () {
image.attr('src', images[newN]);
image.fadeIn();
n = newN;
});
});
});
In my HTML i have 4 image tags like this
<div id="imgContainer">
<img id = "crystal1" src="assets/images/crystal1.jpg" alt="crystal1">
<img id = "crystal2" src="assets/images/crystal2.jpg" alt="crystal2">
<img id = "crystal3" src="assets/images/crystal3.jpg" alt="crystal3">
<img id = "crystal4" src="assets/images/crystal4.jpg" alt="crystal4">
</div>
in my JS file i have this function which picks 4 random values between 1-12 and pushes them into a global array.
function generateCrystalNumber(){
for (var i = 0; i<4; i++){
crystalNumvar = Math.floor(Math.random()*12) + 1;
crystalNumbers.push(crystalNumvar);
}
}
How do I go about assigning each of the values in the array to a different image tag using javascript or jquery ?
Use .each() function and loop over your images, add attribute using data-*
You can get rid of the array and generate random numbers within the .each() function.
function getRandomInt() {
return Math.floor(Math.random()*12) + 1;
}
$(document).ready(function () {
$('img').each(function () {
$(this).attr('data-crystal', getRandomInt());
});
});
var crystalNumbers = [];
function generateCrystalNumber() {
for (var i = 0; i < 4; i++) {
crystalNumvar = Math.floor(Math.random() * 12) + 1;
crystalNumbers.push(crystalNumvar);
}
}
generateCrystalNumber();
$(document).ready(function () {
$('img').each(function (index) {
$(this).attr('data-crystal', crystalNumbers[index]);
})
$('img').on('click', function(){
console.log($(this).attr('data-crystal'));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imgContainer">
<img id="crystal1" src="assets/images/crystal1.jpg" alt="crystal1">
<img id="crystal2" src="assets/images/crystal2.jpg" alt="crystal2">
<img id="crystal3" src="assets/images/crystal3.jpg" alt="crystal3">
<img id="crystal4" src="assets/images/crystal4.jpg" alt="crystal4">
</div>
function generateCrystalNumber(){
var crystalNumbers = [];
for (var i = 0; i<4; i++){
crystalNumvar = Math.floor(Math.random()*12) + 1;
crystalNumbers.push(crystalNumvar);
}
document.getElementById('imgContainer').childNodes.forEach(function(elm){
elm.value = crystalNumbers.shift();
});
}
generateCrystalNumber();
<div id="imgContainer">
<img id = "crystal1" src="assets/images/crystal1.jpg" alt="crystal1">
<img id = "crystal2" src="assets/images/crystal2.jpg" alt="crystal2">
<img id = "crystal3" src="assets/images/crystal3.jpg" alt="crystal3">
<img id = "crystal4" src="assets/images/crystal4.jpg" alt="crystal4">
</div>
// To associate a random number in image's data attribute
$('img').each(function(){
$(this).data('data-random-Number', generateCrystalNumber());
}
function generateCrystalNumber(){
//for (var i = 0; i<4; i++){ -- For loop is not needed
return (Math.floor(Math.random()*12) + 1);
// crystalNumbers.push(crystalNumvar);
//}
}
I think you are looking for a solution where on clicking the image, you want to show a random image due to random number generation.
Below code can be a start.
Code gets image elements references and pushed them to imgElems array.
It calls generateCrystalNumber() so that random numbers are generated and stored in the array
Click event is registered on imgContainer which is a parent div for all the elements.
Inside event handler, the code figures out which image was clicked and changes the src attribute by reading from the random number array.
Note: You may want to tweak the logic further to reset the random numbers as per your requirements
$(document).ready(function () {
var crystalNumbers = [];
var imgElems = [];
var path = "assets/images/crystal";
imgElems.push(document.getElementById('crystal1'));
imgElems.push(document.getElementById('crystal2'));
imgElems.push(document.getElementById('crystal3'));
imgElems.push(document.getElementById('crystal4'));
generateCrystalNumber();
function generateCrystalNumber() {
for (var i = 0; i < 4; i++) {
var crystalNumvar = Math.floor(Math.random() * 12) + 1;
crystalNumbers.push(crystalNumvar);
}
}
$('body').on('click', '#imgContainer',function (e) {
var id = e.target.id;
$('#' + id).attr('src', path + crystalNumbers[id.slice(-1)-1] + ".jpg");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imgContainer">
<img id = "crystal1" src="assets/images/crystal1.jpg" alt="crystal1">
<img id = "crystal2" src="assets/images/crystal2.jpg" alt="crystal2">
<img id = "crystal3" src="assets/images/crystal3.jpg" alt="crystal3">
<img id = "crystal4" src="assets/images/crystal4.jpg" alt="crystal4">
</div>
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]);
We are currently creating an image inside a holder (ch-item) as shown below:
<div class="ch-item ch-img-1" style="background: url(<?php echo get_template_directory_uri(); ?>/images/image1.jpg);">
If possible we would like to make this image change to another when clicked, and repeat this process six times in all, so each time it is clicked it changes to another image.
We would greatly appreciate any help. Thank you!
This is one way to do it using solely Javascript:
// Counter to keep track of which the current image is
var counter = 0;
// List of images
var images = [
'http://cdn.cutestpaw.com/wp-content/uploads/2011/11/Seemly-l.jpg',
'http://cdn.cutestpaw.com/wp-content/uploads/2011/11/Handsome-l.jpg',
// Add more images here
];
window.onload = function () {
// Get the container div
var gallery = document.getElementById('gallery');
// Run updateImage function on click
gallery.addEventListener('click', updateImage);
// Run updateImage on start
updateImage();
}
function updateImage() {
// Get the container div
var gallery = document.getElementById('gallery');
// Set background image
gallery.style.backgroundImage = 'url(' + images[counter] + ')';
// Update counter
counter++;
// Remove old class name
if (counter == 1) { // Remove last
gallery.className = gallery.className.replace(
' ch-img-' + images.length,
''
);
} else { // Remove previous
gallery.className = gallery.className.replace(
' ch-img-' + (counter - 1),
''
);
}
// Add new class name
gallery.className = gallery.className + ' ch-img-' + (counter);
// Reset counter when at the end of the images list
if (counter == images.length) {
counter = 0;
}
}
And here is a JSFiddle to try it out:
https://jsfiddle.net/0tg6up0o/14/
My HTML page has an image with id img. The idea is that by clicking first, previous, or next, the user can navigate through a set of images. How do I do this using JavaScript?
This should be a good start for you:
<script>
var imgs = ["img1.png","img2.png","img3.png"]; // copy images to the same dir
var index = 0;
</script>
<img src="img1.png" onclick="this.src=imgs[++index%imgs.length]"/>
click the image to slide.
If you need buttons, see this example:
<img id="clicker" src="img1.png"/>
Prev
Next
First
Last
<script>
var imgs = ["img1.png","img2.png","img3.png"];
var index = 0;
var clicker = document.getElementById("clicker");
function prev() { clicker.src = imgs[--index%imgs.length]; }
function next() { clicker.src = imgs[++index%imgs.length]; }
function first() { clicker.src = imgs[index=0]; }
function last() { clicker.src = imgs[index=imgs.length-1]; }
</script>
The return false means that default action on click (follow the link) is supressed. Javascript can access elements i.e. using id (see clicker here). Once you get comfortable with this and you start to solve browser compatibility problems, it is good idea to continue with jQuery (as the other suggests), MooTools or other framework.
Use jQuery!
var myImg = $("#myimg");
$("#next").click(function(){
var id = myImg.attr("data-id") + 1;
myImg.attr("src", "image"+id+".jpg");
});
$("#prev").click(function(){
var id = myImg.attr("data-id") -1;
myImg.attr("src", "image"+id+".jpg");
});
HTML:
<img id="myimg" src="image1.jpg" data-id="1">
Next<br>
Previous<br>
This is a very dummy example. There are numerous slideshow plugins out there!
No need jQuery:
<script type='text/javascript'>
window.onload = function() {
var imageSrcs= ['1.jpeg', '2.jpg', '3.jpg'];
var index = 0;
var image = document.getElementById('img');
var previous = document.getElementById('previous');
previous.onclick = function() {
index -= 1;
if(index < 0) index = imageSrcs.length - 1;
image.src = imageSrcs[index];
}
var next = document.getElementById('next');
next.onclick = function() {
index += 1;
if(index == imageSrcs.length) index = 0;
image.src = imageSrcs[index];
}
}
</script>
And html:
<img src='1.jpeg' id='img'>
<div>
<span id='previous'>Previous</span>
<span id='next'>Next</span>
</div>
You do not need a library for this. Something like this will change the image url, where "theImg" is the id of the image:
document.getElementById("theImg").src = "newUrl.png";
To do it without explicit ids, this will change the url where i is the index of the image:
document.getElementsByTagName("img")[i].src = "newUrl.png";
Try something like this (untested):
LOAD JQUERY:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
JAVASCRIPT:
<script type='text/javascript'>
var lst_src = ['img1.jpg', 'img2.png', 'img3.gif'];
$('a', '#nav').click(function(e) {
e.preventDefault();
var src_current = $('#img').attr('src');
var index = lst_src.indexOf(src_current);
var len = lst_src.length;
var action = $(this).attr('class');
switch ($action) {
case 'previous' : var i = index - 1;
if (i < 0) src_current = lst_src[len + i];
else src_current = lst_src[i];
break;
case 'next' : var i = index + 1;
if (i > len) src_current = lst_src[i - len];
else src_current = lst_src[i];
break;
case 'first' : src_current = lst_src[0];
break;
case 'last' : src_current = lst_src[len - 1];
break;
}
$('#img').attr('src', src_current);
});
</script>
HTML: Use the class of a link to denote the required action:
<img id='img' src='img1.jpg'>
<p id='nav'>
<a href='' class='first'>←←First</a>
<a href='' class='previous'>←Previous</a>
<a href='' class='next'>Next→</a>
<a href='' class='last'>Last→$rarr;</a>
</p>