Javascript Click Function Broken in Gallery Script - javascript

I'm trying to create a gallery script with JS (I've only been learning for a week so please excuse if I've made any ridiculous mistakes!). When I run the code, I get an error for controlLeft.onclick = changeImage(--);, saying ( is an unexpected token.
By my untrained eye everything should be fine, but evidently not. What have I done wrong here:
//Javascript Image Changer
var currentImage = document.getElementById("currentImage");
var imageArray = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg"];
var imageIndex= 0;
function changeImage(param){
currentImage.setAttribute("src", imageArray[imageIndex]);
imageIndex[param];
if (imageIndex >= imageArray.length){
imageIndex = 0;
}else if(imageIndex <= -1){
imageIndex = imageArray.length + 1;
}
}
var controlLeft = document.getElementById("left");
var controlRight = document.getElementById("right");
controlLeft.onclick = changeImage(--);
controlRight.onclick = changeImage(++);

You can't just pass operators around like other things. Even in a programming language with higher-order functions the same thing usually does not apply to operators.
Besides that, onclick expects a function - not the result of a function call.
Here's a snippet that is likely to work:
function changeImage(mod){
currentImage.setAttribute("src", imageArray[imageIndex]);
imageIndex += mod;
if (imageIndex >= imageArray.length){
imageIndex = 0;
}else if(imageIndex <= -1){
imageIndex = imageArray.length + 1;
}
}
var controlLeft = document.getElementById("left");
var controlRight = document.getElementById("right");
controlLeft.onclick = function() { changeImage(-1); };
controlRight.onclick function() { changeImage(1); };

Just make a slight modification:
controlLeft.onclick = function() {
changeImage('back');
};
controlRight.onclick = function() {
changeImage('forward');
};

Related

My javascript slidshow code is not working

I have no clue why.
I have checkt everything but it should work.
This shuld be a slidshow for a webseit
<script src="JS/javascript.js">
"use strict";
var image = ['"bilder/1.png"','"bilder/2.png"'];
var i = 0;
aengereHintergrund();
function aengereHintergrund() {
document.getElementById('hintergund').style.backgroundImage = 'url('+image[i]+')';
if(i < image.length){
i ++
}
else {
i = 0
}
setTimeout(aengereHintergrund(),3000);
}
</script>
Oh, the classic function reference vs invocation problem.
Here's what you wrote:
setTimeout(aengereHintergrund(),3000);
And here's what you should have written:
setTimeout(aengereHintergrund,3000);
In the second case, we're passing the function aengereHintergrund itself to setTimeout, which is what we want. In the first case, you're invoking aengereHintergrund, and passing its result (which is nothing, aka undefined) to setTimeout.
(Note: You should also probably use setInterval instead of setTimeout, so you don't have to invoke it again and again. Also also, instead of branching on i >= image.length you can just use i = (i + 1) % image.length).
If you write if (i < images.length) i++;, i will reach images.length. You can fix this error with i++; if (i >= images.length) i = 0;, or i = (i + 1) % images.length; :
var slides = document.getElementById("slides");
var images = ["v67W6.jpg", "USehe.jpg"];
var path = "https://i.stack.imgur.com/";
var i = 0;
nextSlide();
function nextSlide () {
var bg = "url(" + path + images[i] + ")";
slides.style.backgroundImage = bg;
i = (i + 1) % images.length;
setTimeout(nextSlide, 1000);
};
<img id="slides" width="300" height="100" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">

Javascript Not Working When Tab Not Active

So, I have a code here that works perfectly fine when I am viewing it in the active browser tab. But, as soon as I minimize or switch between other tabs of the browser (which is chrome by the way) the code starts giving issues. Here is the code below:
var a = document.getElementById("slidermain");
var b = a.getElementsByTagName("IMG");
var len = b.length;
var noOpac = 0;
var fullOpac = 10;
var imgNumb = 0;
function initFade(count){
imgNumb = imgNumb + count;
if(imgNumb < 0){
imgNumb = len;
}
if(imgNumb > len){
imgNumb = 1;
}
elem = b[imgNumb-1];
startFadeEffect(elem);
}
function startFadeEffect(elem){
var opacSetting = noOpac / 10;
if(noOpac > 10){
opacSetting = 1;
}
elem.style.opacity = opacSetting;
elem.style.display = "block";
noOpac++;
var timer = setTimeout(function() { startFadeEffect(elem); }, 55);
if(opacSetting == 1){
clearTimeout(timer);
elem.style.opacity = 1;
noOpac = 0;
setTimeout(function() { endFadeEffect(elem); }, 2000);
}
}
function endFadeEffect(elem){
var opacSetting = fullOpac / 10;
if(fullOpac < 0){
opacSetting = 0;
}
elem.style.opacity = opacSetting;
fullOpac--;
var timer = setTimeout(function() { endFadeEffect(elem); }, 55);
if(opacSetting == 0){
clearTimeout(timer);
elem.style.opacity = 0;
elem.style.display = "none";
fullOpac = 10;
return false;
}
}
function autoFade(){
var loop = setInterval("initFade(1)", 4000);
}
Please not that I have been looking on this site for the answer, but mostly the ones I have found are JQuery based solutions; however, I am looking for a JavaScript only solution in which I might not have to use the get new date function. Please do not mark my question as duplicate as I have done good research. Thanks!
This is not a problem with your javascript, but with Chrome. Chrome does some weird things with your tabs when they aren't active. Add code to "fix the mess", or account for not the tab being active, to recover after tabbing out and back in.

How do you use increments?

I am not sure how to use increments.
through a function. i can't get the paragraph to show the array words
<p id= "demo"
var Array = ["hello", "goodbye"];
var mimg = document.getElementById(imageArray[0]);
mimg.setAttribute('src', [index]);
//var ArrayIndex = 0;
function change() {
("src", Array[Index]);
imageIndex++;
if (Index >= Array.length) {
Index = 0;
}
}
Don't forget to use your browser's console, read this article Using Your Browser to Diagnose JavaScript Errors.
Don't use setattribute function, use src attribute.
var myImage = document.getElementById("mainImage");
var imageArray = ["http://lorempixel.com/400/200/sports/1/", "http://lorempixel.com/400/200/sports/2/", "http://lorempixel.com/400/200/sports/3/", "http://lorempixel.com/400/200/sports/4/"];
myImage.src = imageArray[0];
var imageIndex = 0;
function changeImage() {
myImage.src = imageArray[imageIndex];
imageIndex++;
if (imageIndex >= imageArray.length)
imageIndex = 0;
}
window.onload = function() {
setInterval(function() {
changeImage();
}, 1000);
};
<img id="mainImage" />
var myImage = document.getElementById("mainImage");
var imageArray = ["images/1.png","images/2.png","images/3.png","images/4.png"];
var mimg=document.getElementById(imageArray[0]);
mimg.setAttribute('src',photos[index]);
You aren't showing your relevant HTML, but I notice in this section you are getting an element with ID "images/1.png" and setting the src of that element to the value of something in photos[index]. You haven't shown how the photos array is loaded. Do you actually have an element with an ID "images/1.png"?
In your function, you set the src of the mainImage to the values in imageArray rather than the values in the photo array. That may be valid, but since that is different than what you did outside the function, I want to make sure that was intended.
I think you are talking about such solution:
var imageArr=["images/1.png", "images/2.png", "images/3.png", "images/4.png"];
$('#button'). on('click',function(){
var index=(Math.random(0,imageArr.length)*10)
$('#img').attr('src',imageArr[index])
});
Again you question is not clear, thus I think this will help you to get direction.
This should be solution if you are using plain JavaScript
var myImage = document.getElementById("mainImage"),
imageArray = ["images/1.png", "images/2.png", "images/3.png", "images/4.png"],
imageArrayIndex = 0;
myImage.src = imageArray[imageArrayIndex++];
function changeImage () {
myImage.src = imageArray[imageArrayIndex++];
imageArrayIndex = imageArrayIndex >= imageArray.length ? 0 : imageArrayIndex;
}
Make sure that your element is defined as "img".
Here's a solution which sets a data-index attribute on the image to keep track of the selected index. This solution is compatible with down to IE8 and does not use the Jquery library. Run the code snippet below for a test (click the image to go to the next one).
var mimg = document.getElementById('main-image'),
simg = document.getElementById('sec-image')
imgArr = [
'http://placehold.it/50x50/00AAAA',
'http://placehold.it/50x50/AAAA00',
'http://placehold.it/50x50/AA00AA',
];
var loopImages = function(element, imgArray, startAt) {
var index = element.getAttribute('data-index'),
newIndex = 0;
if (!index)
newIndex = ((startAt && startAt < imgArr.length-1) || 0) + 1;
else if (index < imgArr.length-1)
newIndex = parseInt(index) + 1;
element.setAttribute('data-index', newIndex);
element.src = imgArr[newIndex];
};
mimg.addEventListener('click', function(e) {
loopImages(e.target || e.srcElement, imgArr);
});
setInterval(function() {
loopImages(simg, imgArr);
}, 500);
<p>Preview (click to change)</p>
<img id="main-image" src="http://placehold.it/50x50/00AAAA">
<br>
<p>Preview with interval</p>
<img id="sec-image" src="http://placehold.it/50x50/00AAAA">

Callbacks on Asynchronous Functions with SetInterval?

I'm trying to get something to run after a function using setInterval is done. I'm trying to do this with callbacks but I can't seem to get it work?
So far I have the following
var testing = ['A','D','F','H','B'];
var index = 0;
var wordCount = 1;
var showHide = setInterval(function () {
var displayWords = "";
var mx = index + wordCount;
if (mx > testing.length) mx = testing.length;
for (var i = index; i < mx; i++) {
displayWords += testing[i] + " ";
}
d3.select("#stim").text(displayWords).style("font-size","150px");
index = mx;
if (index > testing.length) {
clearInterval(showHide);
d3.select("#stim").text('L,R').style("font-size","150px");
}
}, 1000);
And I want the following line to execute "after":
d3.select("#stim").text('L,R').style("font-size","150px");
I tried using this method but when I try to put "showHide" in its own function, it doesn't seem to work at all.

How do I set the interval in a for loop?

I'm trying to create a menu of social media icons that slides into and out of the page. The following code works, but it is too fast. It doesn't look like sliding. I think I could adjust the timing using the setInterval() method, but I can't get it to work. This is the code so far:
var socialMedia = document.getElementById("socialmedia");
var stalkMe = document.getElementById("pleasestalkme");
function SM() {
socialMedia.style.position = "fixed";
socialMedia.style.right = "-330px";
}
SM();
stalkMe.addEventListener("click", function(){
if (socialMedia.style.right === "-330px") {
for (i = -330; i <= -30; i++) {
var j = i +"px";
socialMedia.style.right = j;
}
} else if (socialMedia.style.right === "-30px"){
for (i = -30; i >= -330; i--){
var j = i +"px";
socialMedia.style.right = j;
}
}
}, false);
You should have a look at CSS transitions. Basically you just need to change the right style from 300px to 0px and using transition: right 1s; you would see your element being animated
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions
Otherwise, you could have a look at jQuery.... (I feel bad).
Prior to the solution, a word of warning: you actually should not use this code snippet. Instead heed the advice of floribon and look into css transitions.
However, if you absolutely must do it the outmoded way:
for (i = -330; i <= -30; i++) {
var j = i +"px";
socialMedia.style.right = j;
}
write
var hnd;
i = -330;
hnd = setInterval ( function () {
var j = i +"px";
socialMedia.style.right = j;
i++;
if (i > -30) {
clearInterval(hnd); // end activity
}
}, 50 ); // interval length in ms

Categories