Change Image on click (6 Image Loop) - javascript

I have 6 images that I want to swap between by clicking on the image but I can't seem to get the code right in order to make it go to the next picture
HTML
<img src="BCover.jpg" id="ImgGallery" onclick="ImgGallery()"/>
JavaScript
var counter = 1;
ImgGallery.onclick = function (){
if (counter == 1){
document.getElementById("ImgGallery").src = "BCover.jpg";
counter++;
}
else if (counter == 2){
document.getElementById("ImgGallery").src = "MechGP.jpg";
counter++;
}
else if (counter == 3){
document.getElementById("ImgGallery").src = "Mech2.jpg";
counter++;
}
else if (counter == 4){
document.getElementById("ImgGallery").src = "Mech3.jpg";
counter++;
}
else if (counter == 5){
document.getElementById("ImgGallery").src = "Mech4.jpg";
counter++;
}
else if (counter == 6){
document.getElementById("ImgGallery").src = "MCA1.png";
counter==1;
}
};

The problem (other than Spencer's comment about == assignment) seems to be that ImgGallery should be the name of a function, not a reference to the element, as it's being called as a function in the onclick attribute of your img element.
I renamed the ImgGallery() function to rotateGallery to eliminate ambiguity with the id of the element.
I also took some liberty to clean up your code a little by using array cycling instead of a switch statement to handle img gallery rotation.
<img src="BCover.jpg" id="ImgGallery" onclick="rotateGallery()"/>
var counter = 0,
gallery = ["BCover.jpg", "MechGP.jpg", "Mech2.jpg", "Mech3.jpg", "Mech4.jpg", "MCA1.png"],
rotateGallery = function () {
document.getElementById("ImgGallery").src = gallery[counter];
counter++;
if (counter >= gallery.length) {
counter = 0;
}
};

This can be DRYed up a bit. You can include all of your images in an array. JavaScript does not have a native cycle method but you can implement it with the following algorithm.
var images = ["BCover.jpg", "MechGP.jpg", "Mech2.jpg", "Mech3.jpg", "Mech4.jpg", "MCA1.png"];
var gallery = document.getElementById("ImgGallery");
var index = 0;
gallery.addEventListener("click", function() {
gallery.src = images[index];
index = (index === images.length - 1) ? 0 : index + 1;
});
I know the last statement inside the click listener may seem weird, but I wanted to write as little code as possible.

ImageGallery isn't a function, which will cause an error.
However, the main error is counter==1;, on the third last line. The == operator is for testing if a value has equal value (not necessarily equal type though), but for assignment, use the normal = operator.
Try this:
//First, create an array of images (so you can support as many images in the gallery as needed, only needing to update this array)
var images = ["BCover.jpg", "MechGP.jpg", "Mech2.jpg", "Mech3.jpg", "Mech4.jpg", "MCA1.png"],
//and a counter to loop through
c = 0;
//this function is triggered when the image is clicked on sending the image element as a parameter
function nextImg(elem){
//if c is less than the array's length - 1, then add 1 to c, otherwise make c equal 0
c = (c != images.length - 1) ? c + 1 : 0;
//actually change the src attribute of the image
elem.src = images[c];
//and just let you know what image you're up to
document.getElementsByTagName('p')[0].innerHTML = 'Image no. '+(c+1)+'. File name of image: '+images[c];
}
/* Make the image visible */
img{
cursor: pointer;
height: 50px;
width: 50px;
}
<img id='ImageGallery' onclick='nextImg(this)' />
<p>Notice the onclick attribute</p>

Related

Change an image to a new image with Javascript each time the image is clicked

I have a folder of images and I want to replace the one currently being displayed with another image each time that it is clicked on.
I've managed to make this happen once - i.e. to make the if statement work, but I can't get to the elif statement. Why is the elif condition not being met. Everytime I click it just repeats the if statement, even though the console log shows that the backgroundImage is now budgies: url("http://localhost:3000/images_diamonds/budgies.jpg")
// For clicking on the image
document.querySelector('.diamond-pic').addEventListener('click', () => {
let elem = document.getElementById('pic1');
let ht = window.getComputedStyle(elem, null).getPropertyValue("background");
console.log(ht)
if (document.getElementById('pic1').style.backgroundImage="url(../../images_diamonds/ghecko.jpg)") {
document.getElementById("pic1").style.backgroundImage = "url('../../images_diamonds/budgies.jpg'";
console.log('if achieved')
} else if (document.getElementById('pic1').style.backgroundImage="url(../../images_diamonds/budgies.jpg)") {
document.getElementById("pic1").style.backgroundImage = "url('../../images_diamonds/Christmas_Beetle.jpg'";
console.log('else if achived')
} else {
console.log('else achieved')
}
});
The simplest way to do this is to keep the image names in an array and then just advance the image to the next one in the array when it's clicked.
let counter = 0;
let imgs = [
"https://static4.depositphotos.com/1026550/376/i/600/depositphotos_3763236-stock-photo-gold-star.jpg",
"https://previews.123rf.com/images/lineartestpilot/lineartestpilot1803/lineartestpilot180302423/96543894-cartoon-shooting-star.jpg",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTk5tGujYXbv4f9A0pvSuOWC6IhljTzmy4WBw&usqp=CAU",
"http://www.webweaver.nu/clipart/img/nature/planets/smiling-gold-star.png",
"https://upload.wikimedia.org/wikipedia/commons/thumb/3/34/Red_star.svg/2000px-Red_star.svg.png"
];
document.querySelector("img").addEventListener("click", function(event){
this.src = imgs[counter];
// As long as the counter is less than the last index in the array
// increase the counter. Otherwise, start over.
counter = counter < imgs.length-1 ? counter+1 : 0;
});
img { width: 200px;}
<img src="https://previews.123rf.com/images/lineartestpilot/lineartestpilot1802/lineartestpilot180274309/95545188-shooting-star-decorative-cartoon.jpg">
And here's an example when the images are used as backgrounds:
let counter = 0;
let imgs = [
"https://static4.depositphotos.com/1026550/376/i/600/depositphotos_3763236-stock-photo-gold-star.jpg",
"https://previews.123rf.com/images/lineartestpilot/lineartestpilot1803/lineartestpilot180302423/96543894-cartoon-shooting-star.jpg",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTk5tGujYXbv4f9A0pvSuOWC6IhljTzmy4WBw&usqp=CAU",
"http://www.webweaver.nu/clipart/img/nature/planets/smiling-gold-star.png",
"https://upload.wikimedia.org/wikipedia/commons/thumb/3/34/Red_star.svg/2000px-Red_star.svg.png"
];
document.querySelector("div").addEventListener("click", function(event){
this.style.background = "url(" + imgs[counter] + ")";
// As long as the counter is less than the last index in the array
// increase the counter. Otherwise, start over.
counter = counter < imgs.length-1 ? counter+1 : 0;
});
div { width: 300px;
height:300px; border:1px solid black; background:url("https://previews.123rf.com/images/lineartestpilot/lineartestpilot1802/lineartestpilot180274309/95545188-shooting-star-decorative-cartoon.jpg");
}
<div></div>

Having real trouble combining 2 JS

I am struggling combining two JS into one… I try and try in the JSFiddle but can not really understand the console erros…
I am trying to have a background-color that changes combined with a changing background .svg in a div…
$(document).ready(function() {
//Initializing
var i = 0;
var images = []; //array
var time = 3000; // time in millie seconds
//images
images[0] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_1.svg)";
images[1] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_2.svg)";
images[2] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_3.svg)";
images[3] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_4.svg)";
//function
function changeImage() {
var el = document.getElementById('header');
el.style.backgroundImage = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout('changeImage()', time);
}
window.onload = changeImage;
$(function setbackground() {
window.setTimeout( "setbackground()", 2000);
var index = Math.round(Math.random() * 4);
var ColorValue = "FA89CB";
if(index == 1)
ColorValue = "FAED96";
if(index == 2)
ColorValue = "D27DFA";
if(index == 3)
ColorValue = "6CFA64";
if(index == 4)
ColorValue = "8370FA";
document.getElementsByTagName("body")[0].style.backgroundColor = "#" + ColorValue;
});
});
Here's my fiddle:
http://jsfiddle.net/gmck02ru/1/
does somebody have a clue – i guess I am not really understanding what I am doing here so far...
Help please!
The issue is because the syntax you've used to define the setbackground() function is incorrect. You've placed it inside a jQuery object. That function is also never called. You should define it as a standalone function and invoke it when the page loads.
In addition there's a few improvements you can make to the logic.
Use addEventListener() over setting the onclick or other onX event properties.
Declare the elements of the array at the same time as you define the array itself.
Use an array to hold the background colours instead of hard-coding an if statement.
Use the modulo operator when incrementing the counter to save having to write logic to reset to 0
If you want to repeatedly update the background colour, as you do for the images, place the setTimeout() call within the setbackground() function.
Use document.body directly instead of getting it by tag name
$(document).ready(function() {
let i = 0;
let images = [
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_1.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_2.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_3.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_4.svg)"
];
let backgroundColours = ['#FAED96', '#D27DFA', '#6CFA64', '#8370FA']
function changeImage() {
let el = document.getElementById('header');
el.style.backgroundImage = images[i];
i = ++i % (images.length - 1)
setTimeout(changeImage, 3000);
}
changeImage();
function setbackground() {
let index = Math.round(Math.random() * 4);
document.body.style.backgroundColor = backgroundColours[index];
setTimeout(setbackground, 2000);
}
setbackground();
});
Working jsFiddle - see the demo in the fiddle as the images are on an insecure domain so cannot be called from SO.

How do I get my images to fade-in in a gallery using pure JavaScript?

My images are changing but the fade-in effect is not being applied. How do I get it to work? Should I be setting the opacity outside the changeImage() function?
JavaScript beginner here.
SCRIPT:
var imageArray = ["IMG1.jpg","IMG2.jpg",
"IMG3.jpg","IMG4.jpg"];
var imageIndex = 0;
var done = true;
var fading_image = document.getElementById("currentImg");
//To fade image
function function_opacity(opacity_value, fade_in_or_fade_out){
fading_image.style.opacity = opacity_value / 100;
fading_image.style.filter = 'alpha(opacity=' + opacity_value + ')';
if (fade_in_or_fade_out == 'in' && opacity_value == 1) {
fading_image.style.display = 'block';
}
if (fade_in_or_fade_out == 'in' && opacity_value == 100) {
done = true;
}
}
//To change image
function changeImage(){
document.getElementById("currentImg").src = imageArray[imageIndex];
imageIndex++;
if(imageIndex >= imageArray.length){
imageIndex = 0;
}
//Setting opacity
if (done && fading_image.style.opacity != '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout("function_opacity(" + i + ",'in')", i * 5);
}
}
};
setInterval(changeImage, 2000);
HTML
<img src="IMG1.jpg" id="currentImg" alt="Gallery Image">
There are a few reasons this issue may be occurring.
1) You probably need to use an anonymous function with setTimeout that contains the call to function_opacity, as the function takes parameters. setTimeout is expecting a function declaration, not an invocation.
2) Your i value may not be what you think it is. i contains a pointer to a value, not the value itself, and by the time the setTimeout is executed, your for loop has completed. This means that i would be 100 by the time function_opacity is called, making it look like your transition is not working.
Try changing the following code in changeImage and let me know how it goes.
//Setting opacity
if (done && fading_image.style.opacity != '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout(function(){
function_opacity(this, "in");
}.bind(i), i*5);
}
}
I see a problem with your setTimeout implementation. The first argument to setTimeout must be a function reference, as opposed to a function invocation. You are using this concept properly in your setInterval. The visible difference is that you have no '()' after changeImage.
This raises another issue you will need resolved as you are passing arguments to your function_opacity invocation within the setTimeout. Try wrapping your function_opacity function invocation in an anonymous function

Nonconcurrent async recursion

My end goal is to mitigate as much lag (window freezing/stuttering) as possible, giving the client a responsive window from page load.
My program is a Chrome extension, and part of it needs to search through a reddit submission, including all comments for certain words and then do some stuff with them. After this answer, I converted my code to use setInterval for the recursive search. Unforutnately, this runs concurrently, so even though each branch in the comment tree is delayed from its parent, the overall search overlaps each other, negating any benefit in the delay.
I have a solution, but I don't know how to implement it.
The solution would be to have a callback when a branch runs out that goes to the nearest parent fork. This in effect would traverse the comment tree linearly and would allow the setInterval (or probably setTimeout would be more appropriate) to have a noticeable affect.
The code that would need to be changed is:
function highlightComments(){
var elems = $(".content .usertext-body > .md");
var index = 0;
var total = elems.length;
console.log("comments started");
var intId = setInterval(function(){
highlightField(elems.get(index));
index++;
if(index == total){
clearInterval(intId);
addOnClick();
console.log("comments finished");
}
}, 25);
}
and highlightField is:
function highlightField(node) {
var found = $(node).attr("data-ggdc-found") === "1";
var contents = $.makeArray($(node).contents());
var index = 0;
var total = contents.length;
if (total == 0){
return;
}
var intId = setInterval(function() {
if (contents[index].nodeType === 3) { // Text
if (!found){
//Mods
var content = contents[index].nodeValue.replace(new RegExp(data.mods.regex, "gi"), data.mods.replacement);
//Creators
content = content.replace(new RegExp(data.creators.regex, "gi"), data.creators.replacement);
//Blacklist
for (var key in data.blacklist.regex){
if(data.blacklist.regex.hasOwnProperty(key)){
content = content.replace(new RegExp(data.blacklist.regex[key], "gi"), data.blacklist.replacement[key]);
}
}
if (content !== contents[index].nodeValue) {
$(contents[index]).replaceWith(content);
}
}
} else if (contents[index].nodeType === 1) { // Element
highlightField(contents[index]);
}
index++;
if(index == total){
clearInterval(intId);
}
}, 25);
}

Javascript/jQuery change <img src=" "> onclick with loop

I am creating kind of a slideshow in jQuery and on each click of the next button, I need the image src to increase. The file names of the images are 1,2,3,4,5,6,7,8,9,10,11, so I tried using a for loop. But since I'm no javascript/jquery guru, I can't think of other ways to solve my issue and make it actually work.
With my code, nothing happens at all.
This is what I've tried:
$('#right_arrow').click(function()
{
for (i = 1; i <= 11; i++)
{
$('#produkti').attr('src', 'style/images/produktet/' + i + '.gif');
}
});
And this is the actual html for the image:
<img src="style/images/produktet/1.gif" alt="Produkti 1" id="produkti" />
you can not assign one id to same 11 images, it will never work, jquery/javascript will always pick the first element with specified id.
You should use class and pick image element by index.
$('#right_arrow').click(function()
{
for (i = 1; i <= 11; i++)
{
$('.produkti').get(i-1).attr('src', 'style/images/produktet/' + i + '.gif');
}
});
and html here:
<img src="style/images/produktet/6.gif" alt="Produkti 6" class="produkti" />
The logic is - Every time you click that button, the index will return to 1.
for (i = 1; i <= 11; i++)
What you'll need to do, is have a global variable .. say var imgIndex Then, your code should be -
// somewhere ABOVE.. probably the head tag...
var imgIndex = 0;
$('#right_arrow').click(function()
{
$('#produkti').attr('src', 'style/images/produktet/' + imgIndex + '.gif');
imgIndex++;
});
Keep in mind you'll have to reset this imgIndex value when it reaches max.
This is a way to do this with an "auto loop" (when right arrow is clicked and current image is number 11, current image will be number 1)
var current = 6;
$('#right_arrow').click(function()
{
current = (current + 1 <= 11) ? (current + 1) : (1);
$('#produkti').attr('src', 'style/images/produktet/' + current + '.gif');
});
Here's an idea with data tags.
HTML:
<img src="style/images/produktet/1.gif" data-slide="1" data-max="9"/>
JS:
$("#right_arrow").click(function(){
var img = $("#produkti");
var slide = img.data().slide;
var max = img.data().max;
if(slide <= max){
slide ++;
img.attr('src', 'style/images/produktet/' + slide + '.gif');
img.data().slide = slide;
}
});

Categories

Resources