Play and Stop Audio File with Javascript onmouseenter & onmouseleave - javascript

Looking to use just Javascript without any libraries to start and stop audio on mouse enter and mouse leave. Also want the audio to loop while the div is being hovered. Right now I have two divs because I'm unsure of how to add multiple onmouseenter events and if this is even possible. Is all of this possible? Dropping my code snippet below.
document.addEventListener("mousemove", function(){
myFunction(event);
});
var mouse;
var cursor = document.getElementById("cursor");
function myFunction(e){
mouseX = e.clientX;
mouseY = e.clientY;
cursor.style.left = (mouseX-55) + "px";
cursor.style.top = (mouseY-55) + "px";
}
function play() {
var audio = new Audio('https://www.figurefoundry.xyz/metal/metaldrums.mp3');
audio.play();
}
body {
background: #fffdfa;
}
#cursor {
height: 100px;
width: 100px;
position: absolute;
backface-visibility: hidden;
z-index: 9999999;
pointer-events: none; /* pointer-events: none is needed */
cursor: none;
animation: spincursor infinite 1.5s steps(1, end);
}
div {
background: black;
width: 200px;
height: 100px;
margin: 30px;
cursor: none;
}
#keyframes spincursor {
0% {
transform: rotate(0deg);
}
12.5% {
transform: rotate(45deg);
}
25% {
transform: rotate(90deg);
}
37.5% {
transform: rotate(135deg);
}
50% {
transform: rotate(180deg);
}
62.5% {
transform: rotate(225deg);
}
75% {
transform: rotate(270deg);
}
87.5% {
transform: rotate(315deg);
}
100% {
transform: rotate(360deg);
}
}
<img src="https://www.figurefoundry.xyz/metal-cursor.svg" id="cursor" hidden></img>
<div onmouseenter="play()">
<div onmouseenter="cursor.hidden = false" onmouseleave="cursor.hidden=true">
</div> <!--make cursor invisible on leave and visible on enter-->
</div>

I think you're going to get an error in console if you do this in Chrome: Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first You need to interact ( click) something for audio to be played .
https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

Related

CSS chain multiple animations from different classes

I am developing a ReactJs app, I need to animate a bus in a visual path.
The bus should make stops. So the bus first go from A -> B , then when the user click a button it goes from B -> C , ect..
I have already made the animations and the logic
.bus_0 {
animation: move 3s linear forwards;
}
.bus_1 {
animation: move2nd 3s linear forwards;
}
#keyframes move {
20% {
transform: translate(50px, 0px);
}
40% {
transform: translate(50px, 0px) rotate(-90deg);
}
80% {
transform: translate(50px, -130px) rotate(-90deg);
}
100% {
transform: translate(50px, -125px) rotate(0deg);
}
}
#keyframes move2nd {
20% {
transform: translate(100px, 0px);
}
40% {
transform: translate(100px, 0px) rotate(-90deg);
}
100% {
transform: translate(100px, -50px) rotate(-90deg);
}
}
Here I add classNames based on an index
let bus = document.getElementById('bus');
bus && bus.classList.add(`bus_${data.selectedIndex}`);
The problem is when the first animation starts, the bus reachs point B , but for the second animation , it starts from point A.
Example the bus first position (0, 0), after the first animation (100, 100), when the second animation plays it start from (0, 0) but i need it the start from the last position reached.
There must be a better way probably but that is what i got and i think it will solve your problem
So i collect boxes x and y coordinates when animation button clicks and after the animationend event, i collect both x and y coordinates again and calculate difference of them and add to box style.
const firstButton = document.querySelectorAll('button')[0];
const secondButton = document.querySelectorAll('button')[1];
const myBox = document.querySelector('div')
let rectBefore;
let rectAfter;
let positionBeforeX;
let positionBeforeY;
let positionAfterX;
let positionAfterY;
let differenceX;
let differenceY;
firstButton.addEventListener('click', () => {
rectBefore = myBox.getBoundingClientRect();
positionBeforeX = rectBefore.left;
positionBeforeY = rectBefore.top;
myBox.classList.toggle('first');
})
secondButton.addEventListener('click', () => {
rectBefore = myBox.getBoundingClientRect();
positionBeforeX = rectBefore.left;
positionBeforeY = rectBefore.top;
myBox.classList.toggle('second');
})
myBox.addEventListener('animationend', (event) =>{
rectAfter = myBox.getBoundingClientRect();
positionAfterX = rectAfter.left;
positionAfterY = rectAfter.top;
differenceX = positionAfterX - positionBeforeX;
differenceY = positionAfterY - positionBeforeY;
if(myBox.style.left !== ""){
myBox.style.left = `${parseInt(myBox.style.left.split('px')) + differenceX}px`;
myBox.style.top = `${parseInt(myBox.style.top.split('px')) + differenceY}px`;
}
else{
myBox.style.left = `${differenceX}px`;
myBox.style.top = `${differenceY}px`;
}
myBox.classList.remove(`${event.animationName}`);
})
*,
*::before,
*::after {
box-sizing: border-box;
}
body{
min-height: 100vh;
position: relative;
display: grid;
place-content: center;
}
button{
position: absolute;
background-color: greenyellow;
width: 5rem;
height: 5rem;
}
button:nth-of-type(1){
top:5rem;
right: 10rem;
margin-right: 1rem;
}
button:nth-of-type(2){
top:5rem;
right: 5rem;
}
.box{
position:relative;
width: 100px;
height: 100px;
background-color: blue;
}
.first {
animation: first 3.0s linear forwards;
}
.second {
animation: second 3.0s linear forwards;
}
#keyframes first {
20% {
transform: translate(50px, 0px);
}
40% {
transform: translate(50px, 0px) rotate(-90deg);
}
80% {
transform: translate(50px, -130px) rotate(-90deg);
}
100% {
transform: translate(50px, -125px) rotate(0deg);
}
}
#keyframes second {
20% {
transform: translate(100px, 0px);
}
40% {
transform: translate(100px, 0px) rotate(-90deg);
}
100% {
transform: translate(100px, -50px) rotate(-90deg);
}
}
<div class="box"></div>
<button>First Animation</button>
<button>Second Animation</button>

How to fire "animationend" event, when I can't set a CSS animation?

If I set the css animation to "element", it's fine. If the Css animation is not available, how does it function fire like a zero seconds animation in the ES5?
function run() { ... }
element.addEventListener('animationend', run);
Reply for
#Anurag Srivastava,
Am I wrong idea or do I have the following code wrong? Either way, the return value is "".
var el1 = document.getElementById("notAnimation");
console.log(el1.style.animation);
var el2 = document.getElementById("onAnimation");
console.log(el2.style.animation);
div {
padding: 10px;
margin: 20px;
}
#notAnimation {}
#onAnimation {
animation: scale 10s ease-in-out;
}
#keyframes scale {
0% {
transform: scale(1);
opacity: 1;
color: black;
}
50% {
transform: scale(0.95);
opacity: .4;
color: red;
}
100% {
transform: scale(1);
opacity: 1;
color: black;
}
}
<div id="notAnimation">
Not Animation
</div>
<div id="onAnimation">
Animation
</div>
You can check if element.style.WebkitAnimation and element.style.animation contain any value and execute run() if the value is ""
Edit Turns out that .style will return "" for any value. What you need is window.getComputedStyle() along with the property animationName. If it is none, there is no animation, else there is. Check the code below:
var el1 = document.getElementById("notAnimation");
console.log(window.getComputedStyle(el1)["animationName"])
var el2 = document.getElementById("onAnimation");
console.log(window.getComputedStyle(el2)["animationName"])
div {
padding: 10px;
margin: 20px;
}
#notAnimation {}
#onAnimation {
animation: scale 10s ease-in-out;
}
#keyframes scale {
0% {
transform: scale(1);
opacity: 1;
color: black;
}
50% {
transform: scale(0.95);
opacity: .4;
color: red;
}
100% {
transform: scale(1);
opacity: 1;
color: black;
}
}
<div id="notAnimation">
Not Animation
</div>
<div id="onAnimation">
Animation
</div>

jQuery direction-aware hover with CSS3 transition

I am struggling to get direction-aware hover and css transitions to work properly. Basically I am trying to have a grid of elements with a front and back face, and when on hover have a css transition to flip that element to show the back face.
Transition example (without direction-aware): fiddle
As you can see, no matter which way your mouse enters an element it always flips up. I want it to flip whichever way the mouse enters in/out.
Example:
And here is my attempt with direction-aware: fiddle
I am using jQuery to add classes relevant to the mouse in/out direction.
.hover-in-top {}
.hover-in-right {}
.hover-in-bottom {}
.hover-in-left {}
.hover-out-top {}
.hover-out-right {}
.hover-out-bottom {}
.hover-out-left {}
As you can see from the direction-aware example it kind of works but there are major glitches which I can't get my head round. (I've been overthinking this and my brain has just imploded.)
Anyway I hope this makes sense. Thanks.
I have a partial solution to your question.
But I needed to change some of the transitions to animations
$('.box-container .box').each(function() {
$(this).on('mouseenter mouseleave', function(e) {
var $this = $(this),
width = $this.width(),
height = $this.height();
var x = (e.pageX - $this.offset().left - (width / 2)) * (width > height ? (height / width) : 1),
y = (e.pageY - $this.offset().top - (height / 2)) * (height > width ? (width / height) : 1);
// top = 0, right = 1, bottom = 2, left = 3
var dir_num = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4,
directions = ['top', 'right', 'bottom', 'left'];
// If mouse enter
if (e.type === 'mouseenter') {
// Remove all hover out classes
$this.removeClass(function(index, css) {
return (css.match(/(^|\s)hover-out-\S+/g) || []).join(' ');
});
// Add in direction class
$this.addClass('hover-in-' + directions[dir_num]);
}
// If mouse leave
if (e.type === 'mouseleave') {
// Remove all hover in classes
$this.removeClass(function(index, css) {
return (css.match(/(^|\s)hover-in-\S+/g) || []).join(' ');
});
// Add out direction class
$this.addClass('hover-out-' + directions[dir_num]);
}
});
});
* {
box-sizing: border-box;
}
.box-container {
padding: 20px;
width: 600px;
}
.box-container:after {
content: '';
display: block;
clear: both;
}
.box-container .box {
float: left;
width: 50%;
height: 200px;
position: relative;
perspective: 600px;
border: 1px solid transparent;
}
.box-container .box .front, .box-container .box .back {
float: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
transform-style: preserve-3d;
backface-visibility: hidden;
transition: all 1s ease-in-out;
color: white;
font-size: 60px;
}
.box-container .box .front {
background: blue;
transform: rotateX(0) rotateY(0);
z-index: 900;
}
.box-container .box .back {
background: red;
z-index: 800;
}
.box-container .box:hover .front {
z-index: 900;
}
.box-container .box:hover .back {
z-index: 1000;
transform: rotateX(180) rotateY(0);
}
.box-container .box.hover-in-top .front,
.box-container .box.hover-out-bottom .back {
transform: rotateX(-179deg) rotateY(0);
}
.box-container .box.hover-in-top .back,
.box-container .box.hover-out-bottom .front {
animation: Xminus 1s ease-in-out;
}
#keyframes Xminus {
from {transform: rotateX(179deg) rotateY(0);}
to {transform: rotateX( 0deg) rotateY(0);}
}
.box-container .box.hover-in-bottom .front,
.box-container .box.hover-out-top .back {
transform: rotateX(179deg);
}
.box-container .box.hover-in-bottom .back,
.box-container .box.hover-out-top .front {
animation: Xplus 1s ease-in-out;
}
#keyframes Xplus {
from {transform: rotateX(-179deg) rotateY(0);}
to {transform: rotateX( 0deg) rotateY(0);}
}
.box-container .box.hover-in-right .front,
.box-container .box.hover-out-left .back {
transform: rotateY(-179deg);
}
.box-container .box.hover-in-right .back,
.box-container .box.hover-out-left .front {
animation: Yminus 1s ease-in-out;
}
#keyframes Yminus {
from {transform: rotateX(0deg) rotateY(179deg);}
to {transform: rotateX(0deg) rotateY( 0deg);}
}
.box-container .box.hover-in-left .front,
.box-container .box.hover-out-right .back {
transform: rotateY(179deg);
}
.box-container .box.hover-in-left .back,
.box-container .box.hover-out-right .front {
animation: Yplus 1s ease-in-out;
}
#keyframes Yplus {
from {transform: rotateX(0deg) rotateY(-179deg);}
to {transform: rotateX(0deg) rotateY( 0deg);}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box-container">
<div class="box">
<div class="front">FRONT</div>
<div class="back">BACK</div>
</div>
<div class="box">
<div class="front">FRONT</div>
<div class="back">BACK</div>
</div>
<div class="box">
<div class="front">FRONT</div>
<div class="back">BACK</div>
</div>
<div class="box">
<div class="front">FRONT</div>
<div class="back">BACK</div>
</div>
</div>
The problem with animations if that if you leave the div before the animation has ended, the animation will break
But if move slowly, and stay on the divs until the animation ends, this will work ok.
I hope that somebody finds a better solution
I believe that the best way to approach the problem is not to use CSS transitions.
You can easily implement it using jQuery's animate, utilizing jQuery animations queue to keep all of your animations synced.
I modified your example to animate the transition in JavaScript.
Code example

Javascript / jQuery "Dangle" animation

I would like to create an animation in jQuery or preferable pure javascript that makes a div "dangle". I have attached an animated gif that shows the animation. I don't know how recreate this, if it is something I can use an existing jquery easing / animation for or javascript + css animation or how. I also thought about canvas, but that would limit my ability to manipulate content etc.
RESULT:
Thanks to #peirix for helping me out with the CSS animation. Here is the result I was hoping to achieve. http://jsfiddle.net/zeg61pb7/7/
CSS
#box {
width:30px;
height:30px;
position:absolute;
top:100px;
left:100px;
text-indent: 90px;
background-color:#aaaaaa;
transform-origin: top center;
-webkit-transform-origin: top center;
-webkit-animation: dangle 2s infinite;
-webkit-border-top-left-radius: 50%;
-webkit-border-top-right-radius: 50%;
-moz-border-radius-topleft: 50%;
-moz-border-radius-topright: 50%;
border-top-left-radius: 50%;
border-top-right-radius: 50%;
}
#box:after {
position: absolute;
height: 5px;
width: 5px;
background: #aaaaaa;
top: -4px;
left: 12px;
content: '';
border-radius: 50%;
}
.dims {
position: absolute;
height: 10px;
width: 10px;
background: #aaaaaa;
top: 125px;
left: 110px;
border-radius: 50%;
-webkit-animation: movee 2s infinite;
}
#-webkit-keyframes dangle {
0% { -webkit-transform: rotate(0deg); }
5% { -webkit-transform: rotate(30deg); }
10% { -webkit-transform: rotate(-28deg); }
15% { -webkit-transform: rotate(26deg); }
20% { -webkit-transform: rotate(-24deg); }
25% { -webkit-transform: rotate(22deg); }
30% { -webkit-transform: rotate(-20deg); }
35% { -webkit-transform: rotate(18deg); }
40% { -webkit-transform: rotate(-16deg); }
45% { -webkit-transform: rotate(12deg); }
50% { -webkit-transform: rotate(-10deg); }
55% { -webkit-transform: rotate(8deg); }
60% { -webkit-transform: rotate(-6deg); }
65% { -webkit-transform: rotate(0deg); }
}
#-webkit-keyframes movee {
9% { left: 110px; }
10% { left: 120px; }
15% { left: 100px; }
20% { left: 114px; }
25% { left: 106px; }
30% { left: 113px; }
35% { left: 107px; }
40% { left: 111px; }
45% { left: 109px; }
50% { left: 110px; }
}
Well. You don't really need javascript for that. All you need is some CSS love. I made a quick fiddle to show the basics. Just play around with the numbers a bit to get what you want.
http://jsfiddle.net/zeg61pb7/3/
One note, though. Keyframes is still in need of -prefix for webkit browsers (chrome, safari, safari on ios, android etc), so you need to write it once with, and once without the prefix to hit all browsers. (Even IE10 and IE11 supports this)
You can have a try with css3.
Here is an interesting demo in Github.
Hope it helps you.
Indeed CSS3 can work some magic here, but you would still need Javascript to start and stop the animations, on hover or click events, for example.
I've made a small JSFiddle. Try and hover the red box. I've used webkit-prefixes, but you should be able to switch that easily with moz or ms.
The key differences to other suggestions here are
use animation-iteration-count: 1 to make it dangle once and then stop.
use $.on('<prefix>animationStop') to remove the animation class. this hack is needed to restart the animation later on.
I created a Fiddle with an example of how it can be done.
It depends on the transit-Plugin for jQuery.
var count = 0;
var deg = 45;
var minus = 5;
var interval = setInterval(function(){
$ $('#box').transition({
rotate: deg + 'deg',
transformOrigin: 'center top'
}).transition({
rotate: '-'+deg+'deg',
transformOrigin: 'center top'
});
if(count === 5){
clearInterval(interval);
$('#box').transition({ rotate: '0deg' })
}
if(deg > 10){
deg = deg-(minus+5);
}
count++;
}, 300);
A big plus is, that you can chain different transitions and transforms to your element.
But it`s an additional Plugin which must be loaded.

How to activate a CSS3 (webkit) animation using javascript?

Im really stuck. I want a CSS animation I have created (below) to activate on clicking a div. The only way I thought I could do that was using javascript to create an onClick event. However I dont know how to run/refrence the animation that is in my css file. Can anyone help me?
This is the animation in my css file that I want to run by clicking on a div.
#-webkit-keyframes colorchange {
0% {
background-color: red;
opacity: 1.0;
-webkit-transform: scale(1.0) rotate(0deg);
}
33% {
background-color: blue;
opacity: 0.75;
-webkit-transform: scale(1.1) rotate(-5deg);
}
67% {
background-color: green;
opacity: 0.5;
-webkit-transform: scale(1.1) rotate(5deg);
}
100% {
background-color: red;
opacity: 1.0;
-webkit-transform: scale(1.0) rotate(0deg);
}
}
I even tried putting the css in the same file as the javascript (index.html) and used the following code to try and activate it on click, but no luck.
<script>
function colorchange( test )
{
test.style.webkitAnimationName = 'colorchange ';
}
</script>
Please help :)
You're missing the duration and you have a trailing space in the name you assign:
function colorchange( test )
{
test.style.webkitAnimationName = 'colorchange'; // you had a trailing space here which does NOT get trimmed
test.style.webkitAnimationDuration = '4s';
}
Some more infos on #-webkit-keyframes:
http://webkit.org/blog/324/css-animation-2/
update
Some working code.
<html>
<head>
<style>
#-webkit-keyframes colorchange {
0% {
background-color: red;
opacity: 1.0;
-webkit-transform: scale(1.0) rotate(0deg);
}
33% {
background-color: blue;
opacity: 0.75;
-webkit-transform: scale(1.1) rotate(-5deg);
}
67% {
background-color: green;
opacity: 0.5;
-webkit-transform: scale(1.1) rotate(5deg);
}
100% {
background-color: red;
opacity: 1.0;
-webkit-transform: scale(1.0) rotate(0deg);
}
}
</style>
<script>
function colorchange(e) {
if (e.style.webkitAnimationName !== 'colorchange') {
e.style.webkitAnimationName = 'colorchange';
e.style.webkitAnimationDuration = '4s';
// make sure to reset the name after 4 seconds, otherwise another call to colorchange wont have any effect
setTimeout(function() {
e.style.webkitAnimationName = '';
}, 4000);
}
}
</script>
</head>
<body>
<div onclick="colorchange(this)">Hello World!</div>
</body>
</html>

Categories

Resources