Show size value of element during CSS transition - javascript

When a user scroll to certain element on my page I add class which starts an animation of the width of it. I starts of with a width of 0% then goes up to 99% for example. As this animates is there a way to display this width incrementing in the page in HTML ie a <p> tag with this value incrementing?
The CSS is just this, I add the class .active when the user scrolls to it with Javascript.
.graph-horiz-bar__bar{
background:$niagara;
top:0px;
position:absolute;
left:0px;
width:0;
height:100%;
transition: width 0.3s;
}
.graph-horiz-bar__bar.active{
width:100%;
transition: width 0.3s;
}

var div = document.getElementById("yourDiv"), parapgraph = document.getElementById("yourParagraph");
setInterval(function(){
paragraph.innerHTML = div.offsetWidth + "px";
}, 20);
This sets the paragraphs content to the div's width every 20 ms.

The simplest way would be to animate the element width using jQuery .animate() and reading the current width from the step: parameter callback (Read the Docs)...
Using CSS3 transition:
var $bar = $("#bar"),
$currWidth = $("#currWidth"),
itv = null;
$("#bar").on({
// START COUNTING THE WIDTH
// I used a custom "start" event cause currently (2016)
// Event.transitionstart is implemented only in IE10+, Edge
start : function(){
$(this).addClass("active");
itv = setInterval(function(){
$currWidth.text($bar[0].offsetWidth);
},10);
},
// STOP COUNTING THE WIDTH
transitionend : function() {
clearInterval(itv);
$currWidth.text("INTERVAL STOPPED");
}
});
$("#start").on("click", function(){ // CLICK JUST FOR DEMO,
// You need to place this trigger inside your inViewport method
// when the element enters the viewport
$bar.trigger("start"); // <<----------------
});
#bar{
height: 20px;
width:0;
background:red;
transition: 3s;
}
#bar.active{
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">ACTIVATE BAR</button><!-- TRIGGER BUTTON JUST FOR DEMO -->
width <span id="currWidth">0</span>
<div id="bar"></div>
When transitionstart will be implemented by all major browsers than the code would look pretty much like:
var itv;
$("#bar").on({
transitionstart: function(){
itv = setInterval(function(){
console.log( $bar[0].offsetWidth );
},10);
},
transitionend : clearInterval(itv)
});
$("#bar").addClass("active"); // place this call where needed
Probably some day in another galaxy some event like transitionstep could be all it takes....
$("#bar").on("transitionstep", function(){ // :(
console.log( this.offsetWidth );
});

Related

transition for addclass only works after first time

I basically have some social media icons at the top of the page, that later become fixed.
I want them to fade in, I was using CSS. Everything I tried using JS did the same thing or didn't work.
Here is my JS:
jQuery(document).scroll(function() {
var y = jQuery(document).scrollTop(), //get page y value
social = jQuery(".socialnetworks"),
headerHeight = jQuery(".bg-cover").height();
if(y >= headerHeight + 500) {
social.css({opacity : 0});
social.addClass("fixedsocialnetworks");
} else {
social.removeClass("fixedsocialnetworks");
}
});
And my CSS
.fixedsocialnetworks {
position: fixed!important;
top: 200px!important;
z-index:10;
left:30px;
opacity:1!important;
transition: opacity 400ms;
}
So I set the opacity to 0, then add a class that sets the opacity to 1, and has the transition.
So it works, but it doesn't work the first time on scroll, it works every other time after the first. Why? How do I fix this?

Jquery - Reverse animation on click (toggle or if/else)

I've tried a lot of different options and I'm sure most would work if I knew what I was doing.
I want to click on an image and make it larger and centered in the screen, then I want to click on the same image and return it back to normal.
In the two individual scripts below I have erased the reverse effect but I basically used functions that changed the css settings back to width:250, height:250, and marginLeft:9%. All I could get it to do successfully was enlarge an image but then it shrank automatically once it had fully enlarged. I need to make the function enlarge and then wait until I click the image again for it to shrink.
<script>
$('document').ready(function(){
$('.hello_mom').on('click', function(){
$('.lbs_lease').animate({
width:"350px",
height:"350px",
zIndex:"10",
marginLeft:"28.4%"
}, 500 );
});
});
</script>
<!--<script>//My idea with this second script was to set an initial variable that I would use to make the enlargement animation run (with an if statement) and the shrinking animation stop until the variable was changed at the end of the function. Once the variable changes the else statement would become true and run my reverse animation. However, it seems redundant when the animation still doesn't wait for another click to occur before it runs.
$a = 5;
$c = 10;
var b = $a;
if(b < $c) {
$('.lbs_lease').animate({
width:"350px",
height:"350px",
zIndex:"10",
marginLeft:"28.4%"
}, 500 )};
</script>-->
you have 2 ways to do that ..
1- by using addClass and removeClass with transition
in css
.imageClicked{
width:350px;
height:350px;
zIndex:10;
marginLeft:28.4%;
transition : 0.5;
}
js
$('document').ready(function(){
$('.hello_mom').on('click', function(){
if($('.lbs_lease').hasClass('imageClicked')){
$('.lbs_lease').removeClass('imageClicked');
}else{
$('.lbs_lease').addClass('imageClicked');
}
});
});
2- by make another animate with default style and use boolean true or false
$('document').ready(function(){
var imgClicked = true;
$('.hello_mom').on('click', function(){
if(imgClicked == true){
$('.lbs_lease').animate({
width:"350px",
height:"350px",
zIndex:"10",
marginLeft:"28.4%"
}, 500 );
imgClicked = false;
}else{
$('.lbs_lease').animate({
//type your default style here
}, 500 );
imgClicked = true;
}
});
});
something like this:
var left = true;
$('.hello_mom').on('click', function () {
if (left) {
$(this).animate({
'marginLeft': "-=30px"
});
left = false;
} else {
$(this).animate({
'marginLeft': "+=30px"
});
left = true;
}
});
http://jsfiddle.net/e1cy8nLm/
You can do something like this: JSFiddle Demo
$('img').on('click', function(){
$(this).toggleClass( 'enlarge' );
});
CSS:
img {
// set the initial height and width here so we can animate these properties.
width:100px;
height:100px;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}
// toggle this class with jQuery to enlarge the img on click
.enlarge {
width:200px;
height:200px;
}
One of the methods will be using addClass and removeClass jquery functions keeping track of the current state of image.
The enlarged variable has the current state of the image and toggles it onclick with addition or removal of class.
Note the transition time is mentioned for both the classes, the added/removed as well as the original styling class to prevent abrupt transition while resizing to both states.
Here is a jsfiddle for that : JS FIDDLE DEMO
HTML Code :
<div>
<img class="hello_mom" src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" />
</div>
CSS Code :
.hello_mom{
width:250px;
height:250px;
background : red;
-webkit-transition: all 0.5s; /* Safari */
transition: all 0.5s;
}
.hov_class{
width:350px;
height:350px;
z-index:10;
//margin-left:28.4%;
-webkit-transition: all 0.5s; /* Safari */
transition: all 0.5s;
}
JS Code :
var enlarged=0;
$('document').ready(function(){
$('.hello_mom').on('click', function(){
if(!enlarged){
$('.hello_mom').addClass("hov_class");
enlarged=1;
}
else{
$('.hello_mom').removeClass("hov_class");
enlarged=0;
}
});
});
Take a look at this
http://julian.com/research/velocity/
Velocity is javascript animation, made faster than CSS animation.
...and here you also have a reverse method

Change button background image, text and shape on hover at the same time

I am wondering if it is possible to make a button background image or text change to another text or image along with the button shape on mouse hover?
Say I had a button having a certain text or background image shoving the symbol ✓ (checkmark) and I wish it to change shape (from a circle to a rectangle) and text (from checkmark to the word submit) on mouse hover.
Is it possible using CSS, JS or both?
Without Changing Animations
JSFiddle
If you just want to change the background image and shape, you can use pure CSS
.button {
height:30px;
width:60px;
-webkit-border-radius:15px;
-moz-border-radius:15px;
border-radius:15px;
background-image:url(...)
}
.button:hover {
-webkit-border-radius:0px;
-moz-border-radius:0px;
border-radius:0px;
background-image:url(...)
}
If you want to change the text, you need JavaScript.
<style>
#button {
height:30px;
width:60px;
border-radius:15px;
background-image:url(img1.png);
}
</style>
<script>
function mouseOver() {
document.getElementById("button").style.backgroundImage = "url(img2.png)";
document.getElementById("button").style.borderRadius = "0px";
document.getElementById("button").innerHTML = "Submit";
}
function mouseOut() {
document.getElementById("button").style.backgroundImage = "url(img1.png)";
document.getElementById("button").style.borderRadius = "15px";
document.getElementById("button").innerHTML = "✓";
}
</script>
<div id="button" onmouseover="mouseOver()" onmouseout="mouseOut()">✓</div>
With Changing Animations
JSFiddle
To animate the button, use the
-webkit-transition:all 0.2s;
transition:all 0.2s;
functions. Every property that is changed in the :hover css, is automatically animated with a duration of 0.2 seconds.
If you also want the text to change (in my example fading in and out) it gets a little more complicated. (Disclaimer: My solution is probably not the most elegant one, but it works.)
Add two more classes to your CSS, .fade-out and .fade-in.
.fade-out {
opacity: 1;
animation: fadeOut 0.2s;
}
.fade-in {
opacity: 0;
animation: fadeIn 0.2s;
}
In this case I wanted the text animation to be a little longer than the border animation (I think it looks better), but if they should be the same length, you have to set each of the animations to 0.1s
Then add two #keyframes animations, fadeOut and fadeIn like this:
#keyframes fadeOut {
from {opacity: 1;}
to {opacity: 0;}
}
#keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}
Now the tricky part, the JavaScript:
function mouseIsOver() {
btn = document.getElementById("button_java");
btn.childNodes[0].className += ' fade-out';
setTimeout(function(){
btn.childNodes[0].innerHTML = "Submit";
btn.childNodes[0].className = btn.childNodes[0].className.replace(' fade-out', '');
btn.childNodes[0].className += ' fade-in';
setTimeout(function(){
btn.childNodes[0].className = btn.childNodes[0].className.replace(' fade-in', '');
}, 200);
}, 200);
}
function mouseIsOut() {
btn = document.getElementById("button_java");
btn.childNodes[0].className += ' fade-out';
setTimeout(function(){
btn.childNodes[0].innerHTML = "✓";
btn.childNodes[0].className = btn.childNodes[0].className.replace(' fade-out', '');
btn.childNodes[0].className += ' fade-in';
setTimeout(function(){
btn.childNodes[0].className = btn.childNodes[0].className.replace(' fade-in', '');
}, 200);
}, 200);
}
childNodes[0] gets all inner children (tags), and chooses the first one
className += ' fade-out' adds the class 'fade-out' to the elements class list. There needs to be a space in front of the added class name, just so if there are classes already defined, they won't combine into one non-existent class
setTimeout(function,waitduration) runs the code in function after it waitet waitduration milliseconds. Match this length to the duration of your animation in the .fade-out{...} class in your CSS-file
className.replace(' fade-out','') replaces the fade-out class in the elements list of classes with an empty string to remove it. Don't forget to remove the space, too.
Your Personalized Button
JSFiddle or PasteBin
I've copied the code from your page, added a <p> wrap around the text in the button, and added
.button p {
line-height:1em;
margin:0;
}
to the CSS.
Then you need to import jQuery by adding
<script src="http://code.jquery.com/jquery-2.1.3.js"></script>
into the head. Then add another code snippet,
<script type="text/javascript">
$( document ).ready(function() {
$("#subscribe_button").hover(
function() {
txt = $("#subscribe_button").children("p");
txt.fadeOut(100, function() {
txt.html("Sottoscrivi");
txt.fadeIn();
});
}, function() {
txt = $("#subscribe_button").children("p");
txt.stop(true,false).fadeOut(100, function() {
txt.html("✓");
txt.fadeIn();
});
}
);
});
</script>
That should be it!

jquery infinite slider images

I'm trying to create an infinite slider using jquery. My page has some tags, with the width equal to the window width.
I want to slide every image after 10 seconds, and when the last image comes up and it's time for the first image to show, I want it to come still from the right.
Now I created a div with a big width, 10000px to hold my unordered list of images and they have display:none. My question is why when I'm giving margin-left: -1000px for one list item, the images appear to overlap one above the other, instead of appearing one after the other. I tried to take a screenshot but I don't know what is happening with my dropbox.
This is my CSS:
.slider {
position: relative;
height: 498px;
/*display: inline-block;*/
overflow: hidden;
}
.slider-list {
/*display: inline-block;*/
float: left;
padding: 0;
margin: 0;
width: 10000px
/*height: 496px;*/
}
.slider-list li{
display: inline-block;
/*float: left;*/
/*width: 100%;*/
height: 496px;
z-index: 1;
And here is my HTML:
<div class="slider">
<ul class="slider-list">
<li><img class="homepage-img"src="images/homepage.jpg"></li>
<li><img class="homepage-img"src="images/image1.jpg"></li>
<li><img class="homepage-img"src="images/image2.jpg"></li>
<li><img class="homepage-img"src="images/image3.jpg"></li>
<li><img class="homepage-img"src="images/image4.jpg"></li>
</ul>
The div with the class .slider will close after some more elements.
UPDATE:
This is my jQuery code since I written this post:
$(document).ready(function(){
slide();
});
slide = function() {
var img = $('.homepage-img');
var content = $('.slider-content');
var slider = $('.slider-list');
var elements = $('.slider-list li').children();
var auto_slide_speed = 100;//ms
var timer;
var i = 0;
img.width($(window).width());
$("li").width($(window).width());
img.height($('.slider-list').height());
content.height($('.slider-list').height());
var img_width = $('.slider-list li').outerWidth();
console.log($('.slider-list li').length);
console.log(elements);
//calculam margin-left = -latimea unei imagini
// while(1)
// {
var left = parseInt(slider.css('margin-left')) - img_width;
for(i = 0; i <= $('.slider-list li').length; i++)
{
console.log(i);
slider.animate({
"margin-left": "+=" + left},
1500,
function() {
// $('.slider-list li:last').after($('.slider-list li:first'));
// $('slider').css({'margin-left' : '0px'});
});
// left = left + left;
// $('slider li').append($(elements[i]).clone());
}
console.log(i);
}
With this, my slider ony goes as far as my list goes. How do I append the first item after the last item and so on so it can be infinite?
If you are targeting modern browsers that support transitions and transforms i would do it that way..
Demo at http://jsfiddle.net/gaby/dbLu5/
jQuery
var slides = $('.slider-list li'); // cache a reference to the slides
setInterval(function(){
var current = slides.filter('.current'), // find slide in view
next = current.next(); // find next slide
if (!next.length){next = slides.first();} // loop if at last slide
slides.removeClass('off'); // reposition already viewed slides to the right
current.removeClass('current').addClass('off'); // set current slide to animate left
next.removeClass('off').addClass('current'); // set next slide to slide in view
}, 10000); // set the interval
CSS (you need to add vendor prefixes for the transform and transition properties)
.slider-list {
position:relative;
padding: 0;
margin: 0;
overflow:hidden;
height: 496px;
}
.slider-list li {
width:100%;
height: 100%;
display: block;
z-index: 1;
transition:transform 1s;
transform:translateX(100%);
left:0; top:0;
position:absolute;
overflow:hidden;
}
.slider-list li.current{
transform:translateX(0%);
z-index:100;
}
.slider-list li.off{
transform:translateX(-100%);
z-index:100;
}
Here is a FIDDLE that will get you started.
Put all your images in a hidden div
Clone them and put them in the visible div
Animate the image by changing the left margin
You can adjust the time between images by the set interval function
You can adjust the slidein time by the animate time.
Because it's an infinite loop, I put the button in to stop the animation any time you want.
JS
var pictxtnumber = 1;
loadpictxt(pictxtnumber);
var fadeintime = 500;
animatediv();
function animatediv()
{
var number = 0;
var interval = setInterval(function() {
pictxtnumber = pictxtnumber + 1;
if(pictxtnumber > 6)
{
pictxtnumber = 1;
}
loadpictxt(pictxtnumber);
$('#stopanim').on('click', function(){
clearInterval(interval);
});
}, 1000);
}
function loadpictxt(num)
{
$('.picturediv').html('');
$(".hiddenimage img:nth-child(" + num + ") ").clone().appendTo('.picturediv');
$('.picturediv img').css('margin-left', '100px');
$('.picturediv img').animate({marginLeft: "0"}, 100);
}
I've made two simple jquery plugins for that:
https://github.com/lingtalfi/jItemSlider
https://github.com/lingtalfi/jInfiniteSlider
I recommend the item slider because the items are forced to be aligned, and it's simpler in the end.
Now to answer your question: How do I append the first item after the last item and so on so it can be infinite?
You could just display your slider items two times (or more) in a row.
Given your html code:
var jSliderList = $(".slider-list");
var jSliderOriginalItems = $("li", jSliderList); // keep track of this one
function init(){
jSliderList.append(jSliderOriginalItems.clone()); // should work, not tested
}
Then with css, you would narrow the slider to the width of your choice.
Suggestions:
I would suggest that you append a page rather than just one item.
A basic approach would be to encapsulate things into functions, like this:
slideToRight()
appendItemsToTheRight()
removeUnecessaryItemsToTheLeft()
slide()
To perform the slide, you could use css transitions.
In your css, put something like this:
.sliderContainer {
transition: transform 2s ease;
}
And then in your js code, to slide, just use a function such as:
function moveSlider(the_offset) {
jSliderContent.css({
transform: "translate3d(" + the_offset + "px, 0px, 0px)"
});
}
Now to actually append an item, you could use a renderItem function to generate them, instead of cloning things.

CSS3 and Javascript: fade text out and then in using the same function

I'm trying to create a fading out and fading in effect using JavaScript and CSS3. The goal is to have a div shrink in width when clicked and have the text contained within it simultaneously fade out. Then when it is clicked again, the div expands back to its normal width, and the text fades back in.
Here is the HTML:
<div id="box1" onclick="slide1()">
<p class="fader">Lorem ipsum.</p>
</div>
Here is the CSS:
#box1 {
position:relative;
left:0%;
top:0%;
width: 70%;
height: 100%;
background-color: #666;
z-index:4;
}
Here is the javascript:
var box1
var fader
window.onload = function() {
box1 = document.getElementById('box1');
fader = document.getElementsByClassName('fader');
}
function slide1(){
if(box1.style.width=='10%'){
box1.style.width='70%';
fader[0].style.opacity='1';
fader[0].style.transition='opacity 0.25s ease-in';
}
else {
box1.style.width='10%';
fader[0].style.opacity='0';
fader[0].style.transition='opacity 0.75s ease-in';
}
}
It's working for the fade-out, but for the fade-in it is immediately transitioning from 0 opacity to 1 opacity... there's no fade-in. Any ideas?
I actually asked a very similar question with the same issue a while back: Opacity effect works from 1.0 to 0, but not 0 to 1.0. Check the out and see if it works for you.
Otherwise, try adding a class to the fader element instead of adding a style declaration. Then, in your actual CSS, write the code for the fader element transition.
I guess you use even firefox or opera? I think your code won't work on safari or chrome since transition needs webkit-prefix on those browsers. You can use following code to get transition support:
var transform = (function () {
var transforms = [
'OTransform',
'MozTransform',
'msTransform',
'WebkitTransform'
], transform = 'transform';
while (transform) {
if (document.body.style[transform] === undefined) {
transform = transforms.pop();
} else {
return transform;
}
}
return false;
}());
When im using CSS-transition, sometimes I change transition style and then let browser update changes before changing other styles. You can do this with timeout. On some browsers I have noticed that animation is not working unless doing that (some firefox browsers).
fader[0].style.transition='opacity 0.75s ease-in';
setTimeout(function () {
box1.style.width='10%';
fader[0].style.opacity='0';
}, 4);

Categories

Resources