How to add transition from one function to another in JavaScript? - javascript
I want to add some smooth transition or animation from the mouse enter event to the mouse leave.
JS :
/* mudar cor do logo maior */
var myImage = document.querySelector('img#logo-maior');
myImage.onmouseenter = function() {
var mySrc = myImage.getAttribute('src');
myImage.setAttribute ('src','images/type-logo-coral.png');
}
myImage.onmouseleave = function() {
var mySrc = myImage.getAttribute('src');
myImage.setAttribute ('src','images/type-logo.png');
}
HTML :
<div class="display">
<img id="modelos" src="images/modelos/1.png">
<img id="logo-maior" src="images/type-logo.png" alt="TYPE logo">
<!--
<button type="button" onclick="displayPreviousImage()">Previous</button>
<button type="button" onclick="displayNextImage()">Next</button>
-->
</div>
Use CSS Animation. Add class for each function that will trigger the animation
Try this code
css
.transition1{
animation: fadeIn1 1.5s;
-webkit-animation: fadeIn1 1.5s; ;
opacity: 1;
}
#keyframes fadeIn1{
from{
opacity: 0;
}
to{
opacity: 1;
}
}
#-webkit-keyframeskeyframes fadeIn1{
from{
opacity: 0;
}
to{
opacity: 1;
}
}
.transition2{
animation: fadeIn2 1.5s;
-webkit-animation: fadeIn2 1.5s; ;
opacity: 1;
}
#-webkit-keyframeskeyframes fadeIn2{
from{
opacity: 0;
}
to{
opacity: 1;
}
}
javascript
var myImage = document.querySelector("img#logo-maior");
myImage.onmouseenter = function() {
myImage.classList.remove("transition2");
myImage.setAttribute("class", "transition1");
myImage.setAttribute("src", "../image2.jpg");
};
myImage.onmouseleave = function() {
myImage.classList.remove("transition1");
myImage.setAttribute("class", "transition2");
myImage.setAttribute("src","../image1.jpg"
);
};
html
<div class="display">
<img
id="logo-maior"
src="../img1.jpg"
alt="TYPE logo"
/>
</div>
In your CSS code:
img:hover {
(whatever styles you want for the hovering effect)
transition: all 0.5s ease-out;
}
For more information on transitions visit: https://developer.mozilla.org/en-US/docs/Web/CSS/transition
Related
How to delay html/css load until item is in viewport
I have an animation on a chart but I want the CSS animation to load once it becomes into the users viewport. Currently it loads on the page load but this means that once the user has scrolled to the section the animation has already occurred. The HTML & CSS can be seen below: .chart[data-percent='100'] .outer { stroke-dashoffset: 0; -webkit-animation: show100 2s; animation: show100 2s; } .chart[data-percent='96'] .outer { stroke-dashoffset: 22; -webkit-animation: show96 2s; animation: show96 2s; } .chart[data-percent='77'] .outer { stroke-dashoffset: 123; -webkit-animation: show75 2s; animation: show75 2s; } .chart[data-percent='75'] .outer { stroke-dashoffset: 133; -webkit-animation: show75 2s; animation: show75 2s; } .chart[data-percent='52'] .outer { stroke-dashoffset: 257; -webkit-animation: show52 2s; animation: show52 2s; } .chart[data-percent='50'] .outer { stroke-dashoffset: 267; -webkit-animation: show50 2s; animation: show50 2s; } .chart[data-percent='25'] .outer { stroke-dashoffset: 401; -webkit-animation: show25 2s; animation: show25 2s; } #-webkit-keyframes show100 { from { stroke-dashoffset: 537; } to { stroke-dashoffset: 0; } } #keyframes show96 { from { stroke-dashoffset: 537; } to { stroke-dashoffset: 22; } } #keyframes show75 { from { stroke-dashoffset: 537; } to { stroke-dashoffset: 124; } } #-webkit-keyframes show52 { from { stroke-dashoffset: 537; } to { stroke-dashoffset: 257; } } #-webkit-keyframes show50 { from { stroke-dashoffset: 537; } to { stroke-dashoffset: 267; } } #keyframes show25 { from { stroke-dashoffset: 537; } to { stroke-dashoffset: 401; } } <div class="row stat-wheel"> <div class="col-sm-4"> <p class="stat-figure">52%</p> <figure class="chart" data-percent="52"> <svg width="200" height="200"> <circle class="outer" cx="95" cy="95" r="85" transform="rotate(-90, 95, 95)"/> </svg> </figure> <p class="white center">increase in sales generated through campaigns</p> </div> <div class="col-sm-4"> <p class="stat-figure">77%</p> <figure class="chart" data-percent="77"> <svg width="200" height="200"> <circle class="outer" cx="95" cy="95" r="85" transform="rotate(-90, 95, 95)"/> </svg> </figure> <p class="white center">return on investment in the first 2 months</p> </div> <div class="col-sm-4"> <p class="stat-figure">96%</p> <figure class="chart" data-percent="96"> <svg width="200" height="200"> <circle class="outer" cx="95" cy="95" r="85" transform="rotate(-90, 95, 95)"/> </svg> </figure> <p class="white center">increase in the quality of sales leads generated</p> </div> </div>
You can checkout the intersection observer api, it tells you when an element becomes visible in your viewport. You can listen to it and then start your animation.
A very clean way would be using vanilla JS. Link with explanation // (c) 2017 Chris Ferdinandi var isInViewport = function (elem) { var distance = elem.getBoundingClientRect(); return ( distance.top >= 0 && distance.left >= 0 && distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) && distance.right <= (window.innerWidth || document.documentElement.clientWidth) ); }; var findMe = document.querySelector('.row stat-wheel'); window.addEventListener('scroll', function (event) { if (isInViewport(findMe)) { console.log('In viewport!'); } else { console.log('Nope...'); } }, false);
JavaScript library to animate elements as they scroll into view. https://scrollrevealjs.org/
adding fadein effect with inner.HTML
Looking to fade-in content when using inner.HTML. Current code; <td style="width: 20%;" class="responsive-td" valign="top"> <div id="placeholder1" class="placeholder1" style="color:white;"></div> </td> if (//logic here){ document.getElementById('placeholder1').innerHTML ='add this with fading effect'; setTimeout(addFn1, 300); function addFn1() { document.getElementById('placeholder2').innerHTML ='add this with fading effect';} setTimeout(addFn2, 1200); function addFn2() { document.getElementById('placeholder3').innerHTML ='add this with fading effect';} } I attempted using css however it doesn't create the effect due to setTimeout. Is there a simple solution using CSS or JS? Or even jQuery if need be?
That is easy to do with jQuery, since there are methods for simple animations like this. Have a look at .fadeIn() and .fadeOut(). if (true){ $('#placeholder1').html('add this with fading effect').fadeIn(600); setTimeout(addFn1, 300); function addFn1() { $('#placeholder2').html('add this with fading effect').fadeIn(600);} setTimeout(addFn2, 1200); function addFn2() { $('#placeholder3').html('add this with fading effect').fadeIn(600);} } body{ background-color:black; } .placeholder1{ display:none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <td style="width: 20%;" class="responsive-td" valign="top"> <div id="placeholder1" class="placeholder1" style="color:white;"></div> <div id="placeholder2" class="placeholder1" style="color:white;"></div> <div id="placeholder3" class="placeholder1" style="color:white;"></div> </td>
May be you can try using opacity set to old=zero to new=one while changing text. Option: Using CSS3 and Js(no jquery) document.addEventListener('DOMContentLoaded', function() { var quotes = ["Hello", "there", "everyone"]; var infos = document.querySelectorAll('div.info'); var repeat = Array.prototype.slice; var fadeIn = function(i) { if (!infos[i]) { return; } infos[i].innerHTML = quotes[i]; infos[i].classList.add("open"); }; repeat.call(infos).forEach(function(el) { var callBack = function(e) { var that = this; repeat.call(infos).forEach(function(cur, ind) { if (cur == that) { fadeIn(1 + ind); return false; } }); }; el.addEventListener('webkitAnimationEnd', callBack); el.addEventListener('animationEnd', callBack); }); fadeIn(0); /* trigger fade */ }); .info { opacity: 0; filter: alpha(0%); border: 1px solid #ccc; margin: 1px 2px; } #keyframes fade { from { opacity: 0; filter: alpha(0%); } to { opacity: 1; filter: alpha(100%); } } .info.open { -webkit-animation: fade .3s; -moz-animation: fade .3s; -ms-animation: fade .3s; -o-animation: fade .3s; animation: fade .3s; opacity: 1; filter: alpha(100%); } <div class="info"></div> <div class="info"></div> <div class="info"></div>
Need to add fade in to image om slideshow
I need to add a fade in and fade out annimation to my image on existing code for slide show. The images must fade in /fade out when user click the buttons. Here is my code. HTML: <div id="imageSlider"> <button id="prevBTN" onclick="prev()"> <b>Prev</b> </button> <button id="nextBTN" onclick="next()"> <b>Next</b> </button> </div> Javascript: var images = [ "HTMLcert.jpg", "CSScert.jpg", "javaScriptCert.jpg", "PHPcert.jpg" ]; var num = 0; function next() { var slider = document.getElementById("slider"); num++; if (num >= images.length) { num = 0; } slider.src = images[num]; } function prev() { var slider = document.getElementById("slider"); num--; if (num <= 0) { num = images.length - 1; } slider.src = images[num]; } how can I add fade in and out to existing java script code .
You can add and remove a class to the active slider element in your javascript function like this: var slider = document.getElementById("slider"); slider.className += " active"; setTimeout(function(){ slider.classList.remove("active"); }, 100); And then your css will look something like this: .active { animation: fade 1s; } #keyframes fade { from { opacity: 0; } to { opacity: 1 } }
You can do it using CSS3 annimation , by creating a custom animation , add a class using this last then toggle the class while clicking in the buttons . bellow a working snippet : var images = [ "http://ramg1.net/images/3.jpg", "https://www.gregbowe.com/assets/img/htmlcert.jpg", "http://www.lordlamer.de/wp-content/uploads/2011/02/php-cert.jpg", "http://www.michellekeselgiancola.com/images/certs/uploads/phpcert.jpg" ]; var num = 0; function next() { var slider = document.getElementById("slider"); num++; if (num >= images.length) { num = 0; } slider.classList.remove("fade"); slider.src = images[num]; setTimeout(function(){slider.classList.add("fade");},10); //slider.classList.add("fade"); } function prev() { var slider = document.getElementById("slider"); num--; if (num <= 0) { num = images.length - 1; } slider.classList.remove("fade"); slider.src = images[num]; setTimeout(function(){slider.classList.add("fade");},10); //slider.classList.add("fade"); } /* create the fade custom annimation wich set 0 to 1 opacity on an element */ #-webkit-keyframes fade { 0% { opacity: 0; } 100% { opacity: 1; } } #-moz-keyframes fade { 0% { opacity: 0; } 100% { opacity: 1; } } #-o-keyframes fade { 0% { opacity: 0; } 100% { opacity: 1; } } #keyframes fade { 0% { opacity: 0; } 100% { opacity: 1; } } /* create the class that trigger the annimation */ .fade { -webkit-animation: fade 2s ease; /* Safari 4+ */ -moz-animation: fade 2s ease; /* Fx 5+ */ -o-animation: fade 2s ease; /* Opera 12+ */ animation: fade 2s ease; /* IE 10+, Fx 29+ */ } <div id="imageSlider"> <img id="slider" class="fade" src="http://ramg1.net/images/3.jpg" width="400px" height="80%" /> <button id="prevBTN" onclick="prev()"> <b>Prev</b> </button> <button id="nextBTN" onclick="next()"> <b>Next</b> </button> </div>
Performance-friendly blinking effect
I'd love to add a blinking effect like this, but I think setInterval is overkill for what's mere cosmetic stuff: jQuery(function(){ $("#watch").each(function(){ var $box = $(this); var show = true; setInterval(function(){ var m = moment(); $box.text(show ? m.format('H:mm') : m.format('H mm')); show = !show; }, 500); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src='//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js'></script> <div id="watch">--:--</div> Is there a newer JavaScript API I could be using, or maybe a CSS transition?
Using the CSS provided by this answer, you can do this jQuery(function() { $("#watch").each(function() { var $box = $(this); setInterval(function() { var m = moment(); $box.html(m.format('H') + '<span class="blink_me">:</span>' + m.format('mm')); }, 1000); }); }); .blink_me { animation: blinker 1s infinite; } #keyframes blinker { 50% { opacity: 0; } } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src='//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js'></script> <div id="watch">--:--</div>
For the records, this is the final CSS I wrote based on George's answer: section { font-size: 5rem; } .stop-watch span { animation: blink 1s infinite; } #keyframes blink{ 0% { animation-timing-function: steps(1, end); opacity: 1; } 50% { animation-timing-function: steps(1, end); opacity: 0; } } <section class="stop-watch"> 1<span>:</span>59 </section>
Javascript Text Rotate
Hello guys it's been bugging me all night. I've been trying to get together a word rotate feature that decreases in speed and then eventually stops. Think of it like a word roulette. So i have the words stored in an array and it looks over the words and displays them. Now, i need to decelerate the speed and slowly make it stop and a random lettter, how would i go about this ? <?php $json=file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.18.1/data/en_US/champion.json'); $champions = json_decode($json); ?> <?php $championsArray = array(); foreach($champions->data as $champion){ $championsArray[] = $champion->id; } shuffle($championsArray); $speed = 1000; $count = count($championsArray); var_dump($championsArray); ?> <!DOCTYPE html> <html lang="en" class="demo1 no-js"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery Super Simple Text Rotator Demo 1: Default Settings</title> <meta name="description" content="Rotating text is a very simple idea where you can add more content to a text area without consuming much space by rotating an individual word with a collection of others" /> <meta name="keywords" content="jquery text rotator, css text rotator, rotate text, inline text rotator" /> <meta name="author" content="Author for Onextrapixel" /> <link rel="shortcut icon" href="../file/favicon.gif"> <link rel="stylesheet" type="text/css" href="css/default.css" /> <!-- Edit Below --> <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> <link rel="stylesheet" href="jquery.wordrotator.css"> <script src="jquery.wordrotator.js"></script> </head> <body class="demo1"> <div class="container"> <p><span id="myWords"></span></p> <div class="main"> Go! </div> </div><!-- Container --> <script type="text/javascript"> function eventFire(el, etype){ if (el.fireEvent) { el.fireEvent('on' + etype); } else { var evObj = document.createEvent('Events'); evObj.initEvent(etype, true, false); el.dispatchEvent(evObj); } } function erm() { var cont = $("#myWords"); $(function () { $("#myWords").wordsrotator({ randomize: true, stopOnHover: true, //stop animation on hover words: ['Heimerdinger','Ezreal','Skarner','Nunu','Kennen','Lulu','Morgana','Sejuani','Draven','Nocturne','KogMaw','Jinx','Khazix','Cassiopeia','Fiora','Maokai','Zac','Quinn','Vladimir','RekSai','LeeSin','TwistedFate','MissFortune','Shaco','Vayne','Sivir','Urgot','Nautilus','Annie','Fizz','Janna','Irelia','Karthus','Trundle','Jax','Graves','Leona','Rengar','Amumu','Malzahar','TahmKench','MasterYi','Twitch','Rumble','Nidalee','Shyvana','Veigar','Singed','Riven','Leblanc','Katarina','Azir','Viktor','Poppy','Ahri','Yorick','Aatrox','Brand','Tryndamere','DrMundo','Hecarim','Braum','Nasus','Pantheon','Elise','Velkoz','Swain','Darius','Kayle','Thresh','Nami','Ekko','Alistar','Galio','Warwick','Orianna','Sona','Lux','Ryze','Jayce','Kassadin','Volibear','Blitzcrank','Gangplank','Karma','XinZhao','Ziggs','Malphite','Tristana','Soraka','Anivia','Xerath','Renekton','Shen','Lissandra','Ashe','Mordekaiser','Talon','Zilean','JarvanIV','Rammus','Yasuo','Vi','Bard','Sion','Udyr','MonkeyKing','Akali','Diana','Varus','Kalista','Evelynn','Teemo','Gnar','Garen','Taric','FiddleSticks','Chogath','Zed','Lucian','Caitlyn','Corki','Zyra','Syndra','Gragas','Olaf'] }); }); eventFire(document.getElementById('myWords'), 'click'); } </script> </body> </html> Can anyone figure out a solution for this?
You could modify a bit the wordrotator plugin so that it allows to change the speed on each rotate. You'll have to tweak the animation and the speed increment, but this should give you some ideas: (function ($) { $.fn.wordsrotator = function (options) { var defaults = { autoLoop: true, randomize: false, stopOnHover: false, changeOnClick: false, words: null, animationIn: "flipInY", animationOut: "flipOutY", speed: 40, onRotate: function () {},//you add these 2 methods to allow the effetct stopRotate: function () {} }; var settings = $.extend({}, defaults, options); var listItem var array_bak = []; var stopped = false; settings.stopRotate = function () {//you call this one to stop rotate stopped = true; } return this.each(function () { var el = $(this) var cont = $("#" + el.attr("id")); var array = []; //if array is not empty if ((settings.words) || (settings.words instanceof Array)) { array = $.extend(true, [], settings.words); //In random order, need a copy of array if (settings.randomize) array_bak = $.extend(true, [], array); listItem = 0 //if randomize pick a random value for the list item if (settings.randomize) listItem = Math.floor(Math.random() * array.length) //init value into container cont.html(array[listItem]); // animation option var rotate = function () { cont.html("<span class='wordsrotator_wordOut'><span>" + array[listItem] + "</span></span>"); if (settings.randomize) { //remove printed element from array array.splice(listItem, 1); //refill the array from his copy, if empty if (array.length == 0) array = $.extend(true, [], array_bak); //generate new random number listItem = Math.floor(Math.random() * array.length); } else { //if reached the last element of the array, reset the index if (array.length == listItem + 1) listItem = -1; //move to the next element listItem++; } $("<span class='wordsrotator_wordIn'>" + array[listItem] + "</span>").appendTo(cont); cont.wrapInner("<span class='wordsrotator_words' />"); cont.find(".wordsrotator_wordOut").addClass("animated " + settings.animationOut); cont.find(".wordsrotator_wordIn").addClass("animated " + settings.animationIn); settings.onRotate();//this callback will allow to change the speed if (settings.autoLoop && !stopped) { //using timeout instead of interval will allow to change the speed t = setTimeout(function () { rotate() }, settings.speed, function () { rotate() }); if (settings.stopOnHover) { cont.hover(function () { window.clearTimeout(t) }, function () { t = setTimeout(rotate, settings.speed, rotate); }); }; } }; t = setTimeout(function () { rotate() }, settings.speed, function () { rotate() }) cont.on("click", function () { if (settings.changeOnClick) { rotate(); return false; }; }); }; }); } }(jQuery)); function eventFire(el, etype) { if (el.fireEvent) { el.fireEvent('on' + etype); } else { var evObj = document.createEvent('Events'); evObj.initEvent(etype, true, false); el.dispatchEvent(evObj); } } function erm() { var cont = $("#myWords"); $(function () { $("#myWords").wordsrotator({ animationIn: "fadeOutIn", //css class for entrace animation animationOut: "fadeOutDown", //css class for exit animation randomize: true, stopOnHover: true, //stop animation on hover words: ['Heimerdinger', 'Ezreal', 'Skarner', 'Nunu', 'Kennen', 'Lulu', 'Morgana', 'Sejuani', 'Draven', 'Nocturne', 'KogMaw', 'Jinx', 'Khazix', 'Cassiopeia', 'Fiora', 'Maokai', 'Zac', 'Quinn', 'Vladimir', 'RekSai', 'LeeSin', 'TwistedFate', 'MissFortune', 'Shaco', 'Vayne', 'Sivir', 'Urgot', 'Nautilus', 'Annie', 'Fizz', 'Janna', 'Irelia', 'Karthus', 'Trundle', 'Jax', 'Graves', 'Leona', 'Rengar', 'Amumu', 'Malzahar', 'TahmKench', 'MasterYi', 'Twitch', 'Rumble', 'Nidalee', 'Shyvana', 'Veigar', 'Singed', 'Riven', 'Leblanc', 'Katarina', 'Azir', 'Viktor', 'Poppy', 'Ahri', 'Yorick', 'Aatrox', 'Brand', 'Tryndamere', 'DrMundo', 'Hecarim', 'Braum', 'Nasus', 'Pantheon', 'Elise', 'Velkoz', 'Swain', 'Darius', 'Kayle', 'Thresh', 'Nami', 'Ekko', 'Alistar', 'Galio', 'Warwick', 'Orianna', 'Sona', 'Lux', 'Ryze', 'Jayce', 'Kassadin', 'Volibear', 'Blitzcrank', 'Gangplank', 'Karma', 'XinZhao', 'Ziggs', 'Malphite', 'Tristana', 'Soraka', 'Anivia', 'Xerath', 'Renekton', 'Shen', 'Lissandra', 'Ashe', 'Mordekaiser', 'Talon', 'Zilean', 'JarvanIV', 'Rammus', 'Yasuo', 'Vi', 'Bard', 'Sion', 'Udyr', 'MonkeyKing', 'Akali', 'Diana', 'Varus', 'Kalista', 'Evelynn', 'Teemo', 'Gnar', 'Garen', 'Taric', 'FiddleSticks', 'Chogath', 'Zed', 'Lucian', 'Caitlyn', 'Corki', 'Zyra', 'Syndra', 'Gragas', 'Olaf'], onRotate: function () { //on each rotate you make the timeout longer, until it's slow enough if (this.speed < 600) { this.speed += 20; } else { this.stopRotate(); } } }); }); eventFire(document.getElementById('myWords'), 'click'); } #charset"utf-8"; .wordsrotator_words { display: inline-block; position: relative; white-space:nowrap; -webkit-transition: width 100ms; -moz-transition: width 100ms; -o-transition: width 100ms; transition: width 100ms; } .wordsrotator_words .wordsrotator_wordOut, .wordsrotator_words .wordsrotator_wordIn { position: relative; display: inline-block; -webkit-animation-duration: 50ms; -webkit-animation-timing-function: ease; -webkit-animation-fill-mode: both; -moz-animation-duration: 50ms; -moz-animation-timing-function: ease; -moz-animation-fill-mode: both; -ms-animation-duration: 50ms; -ms-animation-timing-function: ease; -ms-animation-fill-mode: both; } .wordsrotator_words .wordsrotator_wordOut { left: 0; top: 0; position: absolute; display: inline-block; } .wordsrotator_words .wordsrotator_wordOut span { width: auto; position: relative; } .wordsrotator_words .wordsrotator_wordIn { opacity: 0; } #-webkit-keyframes fadeInDown { 0% { opacity: 0; -webkit-transform: translateY(-20px); transform: translateY(-20px); } 100% { opacity: 1; -webkit-transform: translateY(0); transform: translateY(0); } } #keyframes fadeInDown { 0% { opacity: 0; -webkit-transform: translateY(-20px); -ms-transform: translateY(-20px); transform: translateY(-20px); } 100% { opacity: 1; -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } } .fadeInDown { -webkit-animation-name: fadeInDown; animation-name: fadeInDown; } #-webkit-keyframes fadeOutDown { 0% { opacity: 1; -webkit-transform: translateY(0); transform: translateY(0); } 100% { opacity: 1; -webkit-transform: translateY(20px); transform: translateY(20px); } } #keyframes fadeOutDown { 0% { opacity: 1; -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); } 100% { opacity: 1; -webkit-transform: translateY(20px); -ms-transform: translateY(20px); transform: translateY(20px); } } .fadeOutDown { -webkit-animation-name: fadeOutDown; animation-name: fadeOutDown; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="container"> <p><span id="myWords"></span> </p> <div class="main"> Go! </div> </div>