java script animation with mouse enter - javascript

With the "mouse enter" four picture move from left to right.
The animation should start with every "mouse enter".
And there is the problem: After the first "mouse enter" (and the first animation) the second animation only starts after a few seconds have passed. But it should start directly with the second "mouse enter".
Keep looking at the console.log() lines in my code, they explain what I mean.
<!doctype html>
<head>
<style>
* {
margin: 0;padding: 0;
}
</style>
</head>
<body>
<div id="wrapper" style="width:300px;height:250px;border:1px solid #dcdddd; ">
<a id="bild-move-1" href="" target="_blank" style="position: absolute; z-index: 4; margin-left: -75px;"><img src="bild_01-a.jpg" width="75" border="0"></a>
<a id="bild-move-2" href="" target="_blank" style="position: absolute; z-index: 3; margin-left: -75px;"><img src="bild_01-a.jpg" width="75" border="0"></a>
<a id="bild-move-3" href="" target="_blank" style="position: absolute; z-index: 2; margin-left: -75px;"><img src="bild_01-a.jpg" width="75" border="0"></a>
<a id="bild-move-4" href="" target="_blank" style="position: absolute; z-index: 1; margin-left: -75px;"><img src="bild_01-a.jpg" width="75" border="0"></a>
</div>
<script>
//Initialize interval (and variables) outside of the interval
var interval = null;
var indexA = 0;
var ziel = 75;
var numberofThePic = 1;
var currentMove = -75;
//Function to start the animation
function startAnimation() {
//Only set the interval if it hasn't already been set
if (interval == null) {
console.log("active");
console.log(document.getElementById('bild-move-1').style.marginLeft);
interval = setInterval(function() {
if (numberofThePic <=4) {
if (indexA < ziel){
currentMove = currentMove + 1;
document.getElementById('bild-move-'+ numberofThePic).style.marginLeft = currentMove + "px";
indexA++;
} else {
indexA = 0;
numberofThePic = numberofThePic + 1;
}
} else {
//otherwise, animation is complete, clear the interval
reset();
}
}, 10);
}
}
function reset(){
setTimeout(function(){
for (var indexB = 4; indexB >= 1; indexB--) {
document.getElementById('bild-move-'+ indexB).style.marginLeft = -75 + "px";
}
indexA = 0;
numberofThePic = 1;
currentMove = -75;
clearInterval(interval);
interval = null;
console.log("reset");
}, 2000);
}
wrapper.addEventListener("mouseenter", startAnimation);
</script>
</body>
</html>

Related

JavaScript application: trying to make the "wheel" event listener discontinuous fails

I am working on a small "Picture browser" application in Bootstrap 4 and JavaScript.
As can be seen below, there is a "Prev" and a "Next" button that help navigate through the pictures.
I have bean trying to find a reliable method to make mouse well scrolling function the same as these buttons. Scrolling down would be the equivalent of clicking the "Next" button. Scrolling up would be the equivalent of clicking the "Prev" button.
var picArr = $('#pictures_list li');
// The index of the last element of the array is "maxIndex"
var maxIndex = picArr.length - 1;
// Initialize counter
var counter = 0;
var updateCounter = function(btn) {
var direction = $(btn).data("direction")
if (direction === "left") {
if (counter > 0) {
counter--;
} else {
counter = maxIndex;
}
} else {
if (counter < maxIndex) {
counter++;
} else {
counter = 0;
}
}
}
var showCount = function(container_id) {
var pageCount = counter + 1;
document.getElementById(container_id).innerHTML = "Picture " + pageCount + " of " + picArr.length;
}
var showSlide = function() {
var mTop = (200 * counter) * (-1) + 'px';
$('#pictures_list').animate({
'marginTop': mTop
}, 400);
}
showCount('show_count');
$('#controls button').on('click', function() {
updateCounter(this);
showSlide();
showCount('show_count');
});
document.getElementById("picture_frame").addEventListener("wheel", function() {
updateCounter(this);
showSlide();
showCount('show_count')
});
#picture_frame {
width: 200px;
height: 200px;
margin: 5px auto;
border: 1px solid #ccc;
border-radius: 2px;
overflow: hidden;
}
.controls>div {
display: inline-block;
}
#picture_frame {
height: 200px;
overflow: hidden;
}
#pictures_list {
flex-flow: row wrap;
align-items: stretch;
width: 200px;
}
#pictures_list li {
display: flex;
height: 200px;
flex: 1 100%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div id="picture_frame">
<ul id="pictures_list" class="list-unstyled d-flex">
<li><img src="https://picsum.photos/200/200
" alt="First picture"></li>
<li><img src="https://picsum.photos/200/200?gravity=east
" alt="Second picture"></li>
<li><img src="https://picsum.photos/200/200?gravity=west
" alt="Third picture"></li>
<li><img src="https://picsum.photos/200/200?gravity=north
" alt="Fourth picture"></li>
</ul>
</div>
<div class="text-center mb-2">
<span class="badge badge-primary" id="show_count"></span>
</div>
<div class="controls text-center">
<div class="btn-group" id="controls">
<button type="button" class="btn btn-primary btn-sm" data-direction="left">Prev</button>
<button type="button" class="btn btn-primary btn-sm" data-direction="right">Next</button>
</div>
</div>
</div>
Firing the showSlide() function on mouse wheel does work, but the transition is too... continuous. I wish it would be identical to the transition triggered by the buttons.
What am I missing?
Here are several solutions:
-- To prevent the scroll from scrolling multiple images, you can use this function:
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
See https://davidwalsh.name/javascript-debounce-function
-- You should change the parameter of your function updateCounter so that it takes the direction of scrolling images. (example: boolean: true = next, false = previous)
--To recover the direction of the scroll, refer to this answer : https://stackoverflow.com/a/45719399/4864628
var picArr = $('#pictures_list li');
// The index of the last element of the array is "maxIndex"
var maxIndex = picArr.length - 1;
// Initialize counter
var counter = 0;
var updateCounter = function(direction) {
if (direction) {
if (counter > 0) {
counter--;
} else {
counter = maxIndex;
}
} else {
if (counter < maxIndex) {
counter++;
} else {
counter = 0;
}
}
}
var showCount = function(container_id) {
var pageCount = counter + 1;
document.getElementById(container_id).innerHTML = "Picture " + pageCount + " of " + picArr.length;
}
var showSlide = function() {
var mTop = (200 * counter) * (-1) + 'px';
$('#pictures_list').animate({
'marginTop': mTop
}, 400);
}
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
showCount('show_count');
$('#controls button').on('click', function() {
updateCounter($(this).attr('data-direction') == 'left');
showSlide();
showCount('show_count');
});
var pictureFrame = document.getElementById("picture_frame");
var onScroll = debounce(function(direction) {
updateCounter(direction);
showSlide();
showCount('show_count')
}, 100, true);
pictureFrame.addEventListener("wheel", function(e) {
e.preventDefault();
var delta;
if (event.wheelDelta){
delta = event.wheelDelta;
}else{
delta = -1 * event.deltaY;
}
onScroll(delta >= 0);
});
#picture_frame {
width: 200px;
height: 200px;
margin: 5px auto;
border: 1px solid #ccc;
border-radius: 2px;
overflow: hidden;
}
.controls>div {
display: inline-block;
}
#picture_frame {
height: 200px;
overflow: hidden;
}
#pictures_list {
flex-flow: row wrap;
align-items: stretch;
width: 200px;
}
#pictures_list li {
display: flex;
height: 200px;
flex: 1 100%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div id="picture_frame">
<ul id="pictures_list" class="list-unstyled d-flex">
<li><img src="https://picsum.photos/200/200
" alt="First picture"></li>
<li><img src="https://picsum.photos/200/200?gravity=east
" alt="Second picture"></li>
<li><img src="https://picsum.photos/200/200?gravity=west
" alt="Third picture"></li>
<li><img src="https://picsum.photos/200/200?gravity=north
" alt="Fourth picture"></li>
</ul>
</div>
<div class="text-center mb-2">
<span class="badge badge-primary" id="show_count"></span>
</div>
<div class="controls text-center">
<div class="btn-group" id="controls">
<button type="button" class="btn btn-primary btn-sm" data-direction="left">Prev</button>
<button type="button" class="btn btn-primary btn-sm" data-direction="right">Next</button>
</div>
</div>
</div>

Change Image every 20 seconds Javascript with Rows

I found this code from here but I need to add these things in this javascript.
Fade Effect
Want to show images with 2 rows, means I will add 10 images. 5 Images will show on 1st row and 5 images will show in 2nd row.
Want to add Text for every picture e.g. Name and Price
Mouse over image changing stop
<script>
var links = [
"abc.org",
"def.org",
"ghi.org",
"ghi33.org"
];
var images = [
"https://dmcfebaedy6rh.cloudfront.net/product/front/white/spl5596.360x180.1443167798.jpg",
"https://dmcfebaedy6rh.cloudfront.net/product/front/white/mt6050.360x180.1430798334.jpg",
"https://dmcfebaedy6rh.cloudfront.net/product/front/white/pl5087.360x180.1423189940.jpg",
"https://dmcfebaedy6rh.cloudfront.net/product/front/white/spl5596.360x180.1443167798.jpg"
];
var i = 0;
var renew = setInterval(function(){
if(links.length == i){
i = 0;
}
else {
document.getElementById("bannerImage").src = images[i];
document.getElementById("bannerLink").href = links[i];
i++;
}
},10000);
</script>
<a id="bannerLink" href="abc.org" onclick="void window.open(this.href); return false;">
<img id="bannerImage" src="https://d37j5ujucg66b1.cloudfront.net/product/front/white/pl5393.360x180.1456885745.jpg">
</a>
The problem with a question like this is, we have no idea what you're really aiming for. What we need from you is a little bit of code so we can see where you're heading.
I'm sure any number of us could throw together a little carousel that works, but that's not really what this site is for. It's to help people learn and work out what they did wrong or what they need to do to solve a problem.
That being said it would feel wrong of me to write all this without presenting some code.
var caraSel = document.querySelector(".simple-image");
var imageSel = document.querySelectorAll(".bannerLink");
var imageSelMax = imageSel.length - 1;
var imageInt = 0;
var imageIntNext = 1;
var renew = setInterval(function() {
imageSel[imageInt].classList.add("hidden");
imageSel[imageIntNext].classList.remove("hidden");
imageSelMax === imageInt ? imageInt = 0 : ++imageInt;
imageSelMax === imageIntNext ? imageIntNext = 0 : ++imageIntNext;
}, 1000);
caraSel.addEventListener("mouseover", function() {
clearInterval(renew);
});
caraSel.addEventListener("mouseout", function() {
renew = setInterval(function() {
imageSel[imageInt].classList.add("hidden");
imageSel[imageIntNext].classList.remove("hidden");
imageSelMax === imageInt ? imageInt = 0 : ++imageInt;
imageSelMax === imageIntNext ? imageIntNext = 0 : ++imageIntNext;
}, 1000);
});
.simple-image {
position: relative;
width: 360px;
height: 180px;
}
.bannerLink {
position: fixed;
background: #FFF;
top: 0;
left: 0;
will-change: opacity;
transition: opacity .6s ease-in;
text-decoration: none;
color: #000;
}
.bannerLink.hidden {
opacity: 0;
}
<div class="simple-image">
<a class="bannerLink" href="abc.org" onclick="void window.open(this.href); return false;">
<img class="bannerImage" src="https://d37j5ujucg66b1.cloudfront.net/product/front/white/pl5393.360x180.1456885745.jpg">#1
</a>
<a class="bannerLink hidden" href="def.org" onclick="void window.open(this.href); return false;">
<img class="bannerImage" src="https://dmcfebaedy6rh.cloudfront.net/product/front/white/mt6050.360x180.1430798334.jpg">#2
</a>
<a class="bannerLink hidden" href="ghi.org" onclick="void window.open(this.href); return false;">
<img class="bannerImage" src="https://dmcfebaedy6rh.cloudfront.net/product/front/white/pl5087.360x180.1423189940.jpg">#3
</a>
<a class="bannerLink hidden" href="ghi33.org" onclick="void window.open(this.href); return false;">
<img class="bannerImage" src="https://dmcfebaedy6rh.cloudfront.net/product/front/white/spl5596.360x180.1443167798.jpg">#4
</a>
</div>
Sped up of course be you get the idea.

How to set up auto reloading function on slideshow in javascript?

i have slideshow which i want to start with start() and stop with stop(). but it doesn't work. I have defined everything, included stop and start functions. Below i typed my html and javascript codes. When i click on Start button, it doesn't go automatically, i must click each time to get it in process
<DOCTPYPE! >
<html>
<head>
<style>
#imgs img {
float: center;
box-shadow: 5px;
}
input {
float: left;
margin-left: 20px;
}
input:last-child {
margin-left:5px;
}
</style>
<script src="ghgh.js"></script>
</head>
<body>
<div >
<img src="1.jpg" id="myPhoto" style="width: 600px; height: 400px;" />
</div>
<input type="button" value="start" onClick="start();" />
<input type="button" value="stop" onClick="stop();" />
<body>
</html>
javascript:
var myImage = document.getElementById("myPhoto");
var imageArray = ["1.jpg", "2.jpg", "3.jpg", "4.jpg"];
var imageIndex = 0;
function start () {
myPhoto.setAttribute("src", imageArray [imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
var intervalHandle = setInterval (start (), 2000);
function stop() {
clearInterval(intervalHandle);
}
Try this :
var myImage = document.getElementById("myPhoto");
var imageArray = ["1.jpg", "2.jpg", "3.jpg", "4.jpg"];
var imageIndex = 0;
var is_stop = 0;
var time = 0;
function start () {
is_stop =0;
myPhoto.setAttribute("src", imageArray [imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length) {
imageIndex = 0;
}
if(!is_stop){
time = setTimeout(start, 2000);
}
}
function stop() {
is_stop = 1;
if(time){
clearTimeout(time);
}
}

How to move one image randomly when you click on the other image using html & javascript

I am a beginner with javascript. I have two images. One is for clicking, and the other one is for moving 10px to the left & right randomly. Once I click on the "high5" image, "pic2" image has to move randomly in any direction no more than 10 pixels. Every click is added to the score to generate total score at the end. I am stuck at this point, and I don't know where to go. Can someone help me, please?
As you can see, I have edited my code. I'm still having problems in:
Creating scoreboard to keep track of how many clicks the user
clicked within 30 seconds.
I need a timer that counts 30 seconds.
Every time the picture in the middle moves, it keep going to the
left.
HTML code:
<!DOCTYPE html>
<!-- game.html
Uses game.js
Illustrates visibility control of elements
-->
<html lang="en">
<head>
<title>Visibility control</title>
<meta charset="utf-8" />
</head>
<body>
<div id="score">
0
</div>
<div id="high5" style="position: relative; left: 10px;">
<img onclick= "moveImg(); clicked();" src="pics/high5.jpg"
style="height:250px; width:250px; " alt="Minion High Five" />
</div>
<div id="pic2" style="position: relative; top: 20px; left: 650px;">
<img src="pics/pic2.gif" style="height:250px; width:350px;"/>
</div>
<script type="text/javascript" src="game.js" ></script>
</body>
</html>
javascript:
var x = 0;
var y = 0;
var timer = 30;
var count = 0;
var isDone = true;
function moveImg() {
x += Math.floor(Math.random() * 20) - 10;
y += Math.floor(Math.random() * 20) - 10;
pic2.style.left = x + "px";
pic2.style.top = y + "px";
if(timer > 0) {
setTimeout("moveImg()", 50);
timer--;
}
else {
timer = 30;
}
}
function clicked() {
timer = 30;
count++;
score.innerHTML = count;
}
Try something like this: DO not use onclick inside HTML.I have added some jquery part,if you don't need change it accordingly or let me know.
var high5,myVar;
$(function(){
$("img").on("click",function(){
console.log($(this));
if($(this).data('id') == "minion"){
high5=document.getElementById('pic2');
high5.style.left="10px";
moveImg();
}
});
setInterval(function(){ myStopFunction(); }, 3000);//call to stop shacking after 3000 miliseconds.
});
function moveImg() {
//alert("hi");
var x;
x = Math.floor(Math.random()*4)+1;
left = parseInt(high5.style.left.replace('px', ''));
console.log(x+ "," +left);
if (x==4 && left >= 10) {
high5.style.left = (left - 10) + 'px';;
}
if (x==3 && left <= 650) {
high5.style.left = (left + 10) + 'px';
}
if (x==2 && left >= 10) {
high5.style.left = (left - 10) + 'px';;
}
if (x==1 && left <= 450) {
high5.style.left = (left + 10) + 'px';
}
myVar = setTimeout(function(){moveImg();},100);
}
function myStopFunction() {
clearTimeout(myVar);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "high5" style = "position: absolute;">
<img src="pics/high5.jpg" style="height:250px; width:250px;
margin-top: 50px; margin-left: 50px; border:none;"
alt="Minion High Five" data-id="minion"/>
</div>
<div id = "pic2" style=" position: absolute; width:350px;height:250px;margin-left: 550px;border:1px solid black;margin-top:150px;">
<img src="pics/pic2.gif" style="width:350px;height:250px;" alt="Minion High Five"/>
</div>

EBAY slideshow in Javascript tweak required

I have been searching for a slideshow script that works with Ebay, and found http://xlo.co/blog/web-development/javascript-image-fade?quip_thread=blog-post-19&quip_parent=76 this one that seemed to work ok. I wanted to add a third image to the slideshow and that's when things started going south. The following is the code that I altered from the original page to add the third image.
I've put beside any of the code that I inserted. It works, however, the transitions stop working after the first image. If any one can help, it would be greatly appreaciated.
<div id="test">alpha</div>
<div id="slides" style="display: none;">
<div id="slide0" style="background-image: url('/ebay/images/image1.jpg'); width: 670px; height: 240px;">Content0</div>
<div id="slide1" style="background-image: url('/ebay/images/image1.jpg'); width: 670px; height: 240px;">Content1</div>
<!--ADDITION --><div id="slide2" style="background-image: url('/ebay/images/image1.jpg'); width: 670px; height: 240px;">Content2</div>
</div>
<div id="transition" style="width: 670px; height: 240px;">
<!--ADDITION --><div id="imageholder2" style="position: absolute;"></div>
<div id="imageholder1" style="position: absolute;"></div>
<div id="imageholder0" style="position: absolute;"></div>
<!--first last to avoid messing with z-indices-->
</div>
<!-- SCRIPT FUNCTION -->
<script type="text/javascript">
// <![CDATA[
//image transition
var interval = 3000;
var fadeTime = 10;
var currentImage;
var alpha = 100;
var images = new Array();
images[0]=document.getElementById('slide0');
images[1]=document.getElementById('slide1');
<!--ADDITION -->images[2]=document.getElementById('slide2');
var image0Holder = document.getElementById('imageholder0');;
var image1Holder = document.getElementById('imageholder1');;
<!--ADDITION -->var image2Holder = document.getElementById('imageholder2');;
var currentImageHolder = image0Holder;
var currentImage = 0;
var testId = document.getElementById('test');
image0Holder.appendChild(images[0]);
image1Holder.appendChild(images[1]);
<!--ADDITION -->image2Holder.appendChild(images[2]);
function transition() {
function fade() {
if (alpha > 0) {
alpha = alpha - 1;
document.getElementById('test').innerHTML = alpha;
currentImageHolder.style.opacity = (alpha/100);
currentImageHolder.style.MozOpacity = currentImageHolder.style.opacity;
currentImageHolder.style.filter = 'alpha(opacity='+alpha+')';
}
else {
clearInterval(timer0);
document.getElementById('test').innerHTML = "xx";
if (currentImage == image0Holder) {
image0Holder.style.zIndex = 0;
image1Holder.style.zIndex = 1;
<!--ADDITION -->image2Holder.style.zIndex = 2;
alpha = 100;
currentImageHolder.style.opacity = (alpha/100);
currentImageHolder.style.MozOpacity = currentImageHolder.style.opacity;
currentImageHolder.style.filter = 'alpha(opacity='+alpha+')';
currentImageHolder = image1Holder;
image0Holder.removeChild(image0Holder.lastChild);
image0Holder.appendChild(images[currentImage]);
}
else {
image0Holder.style.zIndex = 2;
image1Holder.style.zIndex = 1;
<!--ADDITION -->image2Holder.style.zIndex = 0;
alpha = 100;
currentImageHolder.style.opacity = (alpha/100);
currentImageHolder.style.MozOpacity = currentImageHolder.style.opacity;
currentImageHolder.style.filter = 'alpha(opacity='+alpha+')';
currentImageHolder = image0Holder;
image1Holder.removeChild(image1Holder.lastChild);
image1Holder.appendChild(images[currentImage]);
}
currentImage = (currentImage+1)%images.length;
timer1 = setTimeout(transition, interval);
}
}
timer0 = setInterval(fade, 20);
}
timer1 = setTimeout(transition, interval);
// ]]>
</script>

Categories

Resources