Weird action by javascript for onclick event - javascript

Hi! I'm trying to create a carousel/image slider which is automatic and reactable to onclick event but for somereason the onclick event messesup the automatic flow of the slider even though the code makes perfect sens!
Could someone tell me whats wrong in this code and a solution to fix it please! thank you!
var i = 0;
var images = [];
var time = 3000;
images[0] = "https://cache.lovethispic.com/uploaded_images/162514-Just-Breathe.jpg";
images[1] = "https://cache.lovethispic.com/uploaded_images/162513-Be-Someone-s-Sunshine.jpg";
images[2] = "https://cache.lovethispic.com/uploaded_images/162508-Don-t-Cry-.jpg";
var nextbutton=document.querySelector("#rightbutton");
nextbutton.addEventListener("click",rightbuttonclick);
var prevbutton=document.querySelector("#leftbutton");
prevbutton.addEventListener("click",leftbuttonclick);
function rightbuttonclick(){
i++;
changeImg();
}
function leftbuttonclick(){
i--;
changeImg();
}
function changeImg(){
document.getElementById('startersliders').src = images[i];
if(i < images.length - 1){
i++;
}
else {
i = 0;
}
// Run function every x seconds
setTimeout("changeImg()", time);
}
function changenext(){
i++;
changeImg();
}
// Run function when page loads
window.onload=changeImg;
<button id="leftbutton">left</button>
<img id="startersliders" width="400" height="200"/>
<button id="rightbutton">right</button>

here is a code that can help you,
var prevbutton=document.querySelector("#leftbutton");
//nextbutton.addEventListener("click",leftbuttonclick);
prevbutton.addEventListener("click",leftbuttonclick);

Keep a variable eg: setTime that decides whether to call setTimeout again or not.
function rightbuttonclick() {
i++;
changeImg(false);
}
function leftbuttonclick() {
i--;
changeImg(false);
}
function changeImg(setTime) {
document.getElementById('startersliders').src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
// Run function every x seconds
if (setTime !== false)
setTimeout("changeImg()", time);
}
var i = 0;
var images = [];
var time = 3000;
images[0] = "https://cache.lovethispic.com/uploaded_images/162514-Just-Breathe.jpg";
images[1] = "https://cache.lovethispic.com/uploaded_images/162513-Be-Someone-s-Sunshine.jpg";
images[2] = "https://cache.lovethispic.com/uploaded_images/162508-Don-t-Cry-.jpg";
var nextbutton = document.querySelector("#rightbutton");
nextbutton.addEventListener("click", rightbuttonclick);
var prevbutton = document.querySelector("#leftbutton");
prevbutton.addEventListener("click", leftbuttonclick);
function rightbuttonclick() {
i++;
changeImg(false);
}
function leftbuttonclick() {
i--;
changeImg(false);
}
function changeImg(setTime) {
document.getElementById('startersliders').src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
// Run function every x seconds
if (setTime !== false)
setTimeout("changeImg()", time);
}
// Run function when page loads
window.onload = changeImg();
<button id="leftbutton">left</button>
<img id="startersliders" width="400" height="200" />
<button id="rightbutton">right</button>
Or you can use setInterval instead of setTimeout as shown below:
var i = 0;
var images = [];
var time = 3000;
images[0] = "https://cache.lovethispic.com/uploaded_images/162514-Just-Breathe.jpg";
images[1] = "https://cache.lovethispic.com/uploaded_images/162513-Be-Someone-s-Sunshine.jpg";
images[2] = "https://cache.lovethispic.com/uploaded_images/162508-Don-t-Cry-.jpg";
var nextbutton = document.querySelector("#rightbutton");
nextbutton.addEventListener("click", rightbuttonclick);
var prevbutton = document.querySelector("#leftbutton");
prevbutton.addEventListener("click", leftbuttonclick);
function rightbuttonclick() {
i++;
changeImg(false);
}
function leftbuttonclick() {
i--;
changeImg(false);
}
function changeImg(setTime) {
document.getElementById('startersliders').src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
}
window.onload = changeImg();
setInterval(function() {
changeImg()
}, time);
<button id="leftbutton">left</button>
<img id="startersliders" width="400" height="200" />
<button id="rightbutton">right</button>

add a clearTimeout function to chageImg() and it will work,
as to why it was behaving strangely is because setTimeout was been called multiple times. you should always be careful when using setInverval or setTimeout. here is a code snippet
function changeImg(){
clearTimeout(interval);
document.getElementById('startersliders').src = images[i];
if(i < images.length - 1){
i++;
}
else {
i = 0;
}
// Run function every x seconds
interval = setTimeout("changeImg()", time);
}

Related

Can't pause slideshow with cleartimeout

So I'm learning javascript and I'm currently working on an assignment where I need to create a banner that cycles through multiple images with a pause button, problem is, I can't seem to pause it with clearTimeout()
var images = [];
var timer;
images[0] = 'destaque-home.png';
images[1] = 'destaque-home-1.png';
images[2] = 'destaque-home-2.png';
function changeImg(){
document.MoveBanner.src = images[i];
if(i < images.length - 1){
i++;
} else {
i = 0;
}
var timer = setTimeout("changeImg()", 1000);
console.log(timer);
}
function LeftArrow() {
i--;
if (i < 0){
i=2;
}
document.MoveBanner.src = images[i];
}
function RightArrow() {
document.MoveBanner.src = images[i];
i++;
if (i > 2){
i=0;
}
}
function PauseBut() {
clearTimeout(timer);
}
window.onload = changeImg;```
var timer = setTimeout("changeImg()", 1000);
Because you used var, the variable you create is not the same as the global var timer variable declared at the top of the code. That means that the PauseBut function is trying to clearTimeout with the wrong timer.
To instead use the globally scoped timer:
timer = setTimeout("changeImg()", 1000);

Javascript changing pictures

So I used two images and setInterval to change two pictures continuously over time. When I click on the picture, I will use clearInterval to freeze the image. My question is how do I make the two images change continuously again when I click on it? So it's like a on and off like of scenario. Below is the code which makes the two pictures change continuously and when I click on it, the image freezes and do not change between themselves.
var imageArray = ["_images/korea.jpg","_images/images.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length){
imageIndex = 0;
}
}
var test = setInterval(changeImage, 1000);
myImage.onclick = function(){
clearInterval(test);
}
Instead of clearInterval, use Boolean flag and invert it on click of the image
var imageArray = ["_images/korea.jpg", "_images/images.jpg"];
var imageIndex = 0;
var flag = true;
function changeImage() {
if (flag) {
myImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
}
setInterval(changeImage, 1000);
myImage.onclick = function() {
flag = !flag;
}
Or you can re-initiate setInterval
var imageArray = ["_images/korea.jpg", "_images/images.jpg"];
var imageIndex = 0;
var interval;
var clicked = false;
function changeImage() {
myImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
interval = setInterval(changeImage, 1000);
myImage.onclick = function() {
if (!clicked) {
clearInterval(interval);
clicked = true;
} else {
interval = setInterval(changeImage, 1000);
clicked = false;
}
}
Have a boolean variable to decide if you are going to change the image. Set or reset this boolean variable when you click on the image without clearing the interval.
var active = true;
myImage.onclick = function(){
active = !active;
}
function changeImage(){
if (!active)
return;
myImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length){
imageIndex = 0;
}
}
This might help you :)
<img src="img1.png" id="cimg" onclick="trigger()">
<script>
var imageArray = ["img1.png","img2.png"];
var imageobject = document.getElementById("cimg");
var imagecount = -1;
var changable = true;
function changeimage() {
imagecount++
if(imagecount < imageArray.length) {
imageobject.src = imageArray[imagecount];
}
else {
imagecount = -1;
}
}
function loop() {
if(changable) {
changeimage();
setTimeout(function() { loop(); },1000)
}
}
loop();
function trigger() {
if(changable) {
changable = false;
}
else {
changable = true;
loop();
}
}
</script>
This answer is different to the others because it clears the timer, as opposed to just checking if the flag is set. Your changeImage action stays the same.
var flag = false, timer;
function changeAction() {
if (flag) {
clearInterval(timer);
} else {
timer = setInterval(changeImage, 1000);
}
flag = !flag;
}
changeAction();
myImage.onclick = changeAction;

How to interchange between 2 logos?

I have the following code:
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
var images = new Array (logo1, logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
var images = new Array (logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
Its working well apart from the following bugs:
Image loads even though image already is showing on page.
I have an image onmousehover effect on that image and its causing bad effect.
Is it possible to interchange between the image src and the img onmousehover src?
Thanks
Alex
you can change the src of the img tag using JavaScript as below,
function hover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png');
}
function unhover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png');
}
and the html be
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />
After Edit :
If you want to change it on some timeout, You need to put your below code inside window.onload = function() {}
var images = new Array();
images[0] = "logo_1.png";
images[1] = "logo_2.png";
var images = new Array();
for (var i = 0; i < 2; i++) {
images.push("logo_" + i + ".png");
}
var x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
if (x < 8) {
x += 1;
} else {
x = 0;
}
if (window.addEventListener) {
window.addEventListener('load', changeImg, false);
}
function changeImg() {
var x = 0;
setInterval(function() {
changeImage()
},5000);
}
HTML:
<img id="ad" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png" />
Use jQuery hover to run code when hovering in or out of an element. Also use setTimeout to run code after a delay.
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
$(function() {
$('.logoimage').hover(function() {
setTimeout(function() {
$('.logoimage').attr('src', logo2);
}, 1000);
}, function() {
setTimeout(function() {
$('.logoimage').attr('src', logo1);
}, 1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="logoimage" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png">

Creating an event that changes a picture on mouseover

I'm trying to create an event that changes the picture on mouse over.
var myImage = document.getElementById("mainImage");
var imageArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg",
"_images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"];
var imageIndex = 0;
mainImage.mousover = function changeImage() {
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
// setInterval is also in milliseconds
mainImage.mousover = function () {
var intervalHandle = setInterval(changeImage,1000);
}
myImage.onclick = function() {
clearInterval(intervalHandle);
};
mainImage is an object in HTML and the changeImage function changes current picture.
How should I change my code to make it work?
removed the line that only says "mainImage.mousover =" in the middle
var myImage = document.getElementById("mainImage");
var imageArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg",
"_images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"];
var imageIndex = 0;
function changeImage() {
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
// setInterval is also in milliseconds
mainImage.onmousover = function () {
var intervalHandle = setInterval(changeImage,1000);
}
myImage.onclick = function() {
clearInterval(intervalHandle);
};
You have some type error like:
mainImage.mousover = is syntax error.
change mainImage.mousover to mainImage.onmouseover.
Also you should wrap your code in window.load event handler because it force browser execute your code after image has loaded.
Change code to following:
window.onload = function () {
var myImage = document.getElementById("mainImage");
var imageArray = ["_images/overlook.jpg", "_images/winery_sign.jpg", "_images/lunch.jpg",
"_images/bigSur.jpg", "_images/flag_photo.jpg", "_images/mission_look.jpg"];
var imageIndex = 0;
//mainImage.mousover =
function changeImage() {
myImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
// setInterval is also in milliseconds
var intervalHandle;
mainImage.onmouseover = function () {
intervalHandle = MyImageInterval();
}
document.getElementById("stopButton").onclick = function () {
clearInterval(intervalHandle);
};
function MyImageInterval() {
return setInterval(changeImage, 1000);
}
}
Notice: You should add an input with type = "button" with Id="stopButton".

pausing function on hover

I have a function written in javascript that allows me to scroll through an array of images iterated at a certain interval, now I would like to add some more functionality to it by pausing the rotation when I hover over any of the images in the array.
Javascript
(function() {
var rotator = document.getElementById('bigImage');
var imageDir = '../images/headers/';
var delayInSeconds = 5;
var images = ['ImageOne.png', 'ImageTwo.png', 'ImageThree.png', 'ImageFour.png',
'ImageFive.png',
'ImageSix.png'];
var num = 0;
var changeImage = function() {
var len = images.length;
bigImage.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();​
You could store the id returned from setInterval, and pass it to clearInterval when the image is hovered over.
So, on mouse over, you clear, and on mouse out you set it going again.
Hope that helps!
Use jQuery:
var rotationRunning = true;
var changeImage = function() {
if (rotationRunning) {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len)
num = 0;
}
}
};
$(rotator).hover(
function() { rotationRunning = false; },
function() { rotationRunning = true; }
);

Categories

Resources