Javascript button appear animation - javascript

I have the back to top button that appears when you reach a point on the page, which is working fine, however, when it appears the text is on two lines until the box has finished the animation to appear. So, is there anyway to prevent this? What I mean by the animation is: btt.show('slow');
Code:
$(document).ready(function () {
var btt = $('.back-to-top');
btt.on('click' , function(e) {
$('html, body').animate({
scrollTop: 0
}, 500);
btt.hide('slow');
e.preventDefault();
});
$(window).on('scroll', function () {
var self = $(this),
height = self.height(),
top = self.scrollTop();
if (top > 500) {
btt.show('slow');
} else {
btt.hide('slow');
}
});
});
Example: http://codepen.io/Riggster/pen/WvNvQm

The problem is caused by animating the width of a box, I think it might be better to animate the position of it instead, but - even better - lets use CSS animations!
$(window).on('scroll', function () {
if ($(window).scrollTop() >= 500) {
$(".button").addClass('show');
} else {
$(".button").removeClass('show');
}
});
#wrapper {
width: 100%;
height: 2000px;
}
.button {
position: fixed;
bottom: 50px;
right: -100px;
/* You might still need prefixes here. Use as preferred. */
transition: right 500ms;
}
.button.show {
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="wrapper">
<div class="button">Here's my button!</div>
</div>
I've defined your button as hidden by default, by giving it a position of right: -100px. When we hit the correct scroll position, we add the class show and that triggers the animation performed by CSS and not javascript, as we have the transition property for the property right defined - that way the browser does the heavy lifting.

Toggling show/hide alters your elements width. You either have to put it in a container with display: inline
Or more ideally you might want to change show/hide to jQuery fadeIn() / fadeOut() which is more appropriate for "Back to Top" indicators.
Here is your codepen example modified with inline container:
http://codepen.io/anon/pen/MwWweY

Related

Temporarily Stop One Function Execution with setTimeOut() when a Button is Clicked

I have an animation triggered by a scroll event, which makes a menu slide out of view. There is also a button that when clicked brings the menu back into view.
Because the menu can be closed by scrolling, when the user clicks the button to bring the menu in, if they scroll during this period of the animation, the menu disappears again without the animation completing.
I have put together a simplified version of the animation here http://codepen.io/emilychews/pen/evbzMQ
I need to temporarily prevent the scroll function working after the button is clicked, which I'm assuming would be best done with the setTimeout() method on the click function? I've tried a number of things but can't seem to solve it/ get it to work.
Any help would be awesome. For quick reference as well the code is below
JQUERY
jQuery(document).ready(function($){
// slide menu to left on scroll
function hideOnScroll() {
$(window).scroll(function() {
if ( $(document).scrollTop() > 1) {
$('.menubox').css('left', '-25%');
}
});
}
hideOnScroll(); // call hideOnScroll function
// click handler to bring menu back in
$('.mybutton').on('click', function() {
$('.menubox').css('left', '0%');
var scrollPause = setTimeout(hideOnScroll, 2000) // temporarily pause hideOnScroll function
});
}); //end of jQuery
CSS
body {
margin: 0;
padding: 0;
height: 200vh;}
.menubox {
top: 100;
position: fixed;
width: 20%;
height: 100%;
background: red;
padding: 10px;
color: white;
transition: all 2s;
}
.mybutton {
position: fixed;
left: 40%;
top: 50px;
padding: 5px 10px;
}
HTML
<div class="menubox">Menu Box</div>
<button class="mybutton">Click to bring back menu</button>
** Also please note I've simplified the animation for the sake of the forum, the actual animation function contains Greensock code, but I didn't want to include this in case it confused the issue. I can't therefore just use the .addClass() and .removeClass() or have a workaround that changes the given CSS or scrollTop() values. I need to disable the hideOnScroll() function when the button is clicked for the duration of the click invoked animation - which in the examples is 2s. Thus I think the only way to achieve this is with the setTimeOut() method (i may be wrong on this). But I can't get it to work.
Many thanks
Emily
you can simply check the offset is complete.
function hideOnScroll() {
$(window).scroll(function() {
if ( $(document).scrollTop() > 1) {
if( $('.menubox').offset().left == 0 ){
$('.menubox').css('left', '-25%');
}
});
}
http://codepen.io/anon/pen/aJXGbr
I have made a few changes in your javascript. Have a look
var animating = false;
$(document).ready(function(){
function hideOnScroll() {
$(window).scroll(function() {
event.preventDefault();
if ( $(document).scrollTop() > 1 && !animating){
console.log("Hiding")
animating = true;
$('.menubox').animate({'left': '-25%'},2000,function(){
animating = false;
});
}
});
}
hideOnScroll();
$('.mybutton').click(function() {
var pos = $(window).scrollTop();
animating = true;
$('.menubox').animate({'left':'0%'},2000,function(){
console.log("Finished Opening");
animating = false;
});
console.log("Animating Open");
var siId = setInterval(function(){
if(animating){
console.log("Preventing Window Scrolling.");
$(window).scrollTop(pos);
}
else{
console.log("Stopping setInterval");
animating = false;
clearInterval(siId);
}
},0);
});
});
This will stop your browser window from scrolling until your Menu Open Animation is finished.
Also I have removed the transitionproperty from style.
Tested in Google Chrome.
Kindly inform me if i have misinterpreted your question.

make div scoll untill it reaches top of page then fixed

let's get straight to the point:
My code looks like the following:
<div id="keep_up">
<div id="thread_menu">
<div id="new_thread">
</div>
</div>
</div>
And my css:
#keep_up {
position: fixed;
width: 13%;
}
#thread_menu{
height: 80vh;
width: 100%;
float: left;
position: relative;
}
Now i use this for a forum. and this is basically to show the active and new threads on the side of the screen.
However. When watching a thread, the header disappears (Wich makes sense because we are scrolling down).
but i want the thread menu to stay on my side (So that it is always visible). In this case that is happening because my keep_up div has position: fixed. But i only see half of the thread menu becuase it is too long and won't scroll up.
My question:
I want the thread menu to scroll up, untill it reaches the top of my window. From then on i want it to stay there.
How do i do this?
I saw a few examples but none of them worked for me.
EDIT: Code i tried:
<script src="jquery.min.js">
$(window).scroll(function () {
var margin = null;
$(window).on("scroll", function () {
var scrollHeight = $(document).height(),
scrollTop = $(window).scrollTop(),
offsetBottom = 110, // Offset depending on the height of the footer
offsetTop = 100, // Offset depending on the height of the header
positionTop = $(".keep_up").offset().top,
affix;
if (margin != null && (scrollTop + margin <= positionTop)) {
// The sidebar has reached the bottom and is still on the bottom
affix = false;
} else if (positionTop + $(".keep_up").height() >= scrollHeight - offsetBottom) {
// The sidebar has reached the bottom
affix = 'bottom';
} else if (scrollTop <= offsetTop) {
// The sidebar has reached the top
affix = 'top';
} else {
// The sidebar is midway
affix = false;
}
// If the sidebar hasnot changed his state, return;
if ($(".keep_up").hasClass('at' + (affix ? '-' + affix : ''))) return;
if (affix == 'bottom') {
margin = positionTop - scrollTop;
} else {
margin = null;
}
// If the related class is added to the div
$(".keep_up").removeClass('at at-top at-bottom').addClass('at' + (affix ? '-' + affix : ''))
});
});
</script>
And the CSS:
.keep_up{
/*position: fixed;*/
width: 13%;
}
.keep_up.at {
top: 1px;
position: fixed;
}
.keep_up.at-top{
}
.keep_up.at-bottom {
top: 438px;
position: absolute;
}
modify this on HTML:
<div id="prevent"></div>
<div id="keep_up" data-spy="affix" data-offset-top="200">
Add this CSS:
.affix{position: fixed !important; top:0px; z-index:999;}
.affixpatch{margin-top:100px !important;}
this will fix the div when you scroll down 200px. Change data-offset-top value to reach it on different break point.
.affixpatch is a class that will be loaded with next jquery function. it prevents to hide content behind top fixed div. Change margin-top to another value if this don't solves the "hide content" problem that always generate affixing divs.
<script>
$(function() {
//caches a jQuery object containing the header element
var header = $(".affix");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 200) {
$('#prevent').addClass("affixpatch");
} else {
$('#prevent').removeClass("affixpatch");
}
});
});
</script>
Hope it helps. If not, you may have some class that rewrite or impede the correct function of this affix.
I've tested this hundreds of times, usually to fix navbars.
SCROLL:
Using overflow to scroll content:
#keep_up{
max-height:400px;
width: auto;
overflow:auto;}
This will scroll the content inside #keep_up div (or use it in another one)
NOTE: you must declare a fixed max height for this div. Set max-width only if you need.
You can use %, em, rem... no need to be px for fix the max witdth. (to get a responsive effect, use responsive measurements)
If I understand your scenario correctly, the way to do this might be to use jQuery (or native JS, but you've tagged jQuery so I'm assuming that's in play).
There's a plugin that handles this kind of thing: http://leafo.net/sticky-kit/
I'd suggest you look at the plugin source code to see how it works - an event handler function on $(window).scroll() which then toggles classes on your #thread_menu to fix it in place. To keep your code lightweight, you probably don't need everything the plugin provides.

Page jumps abit up when an element above fades in

I have 2 elements, the first one (at the top) has the following CSS properties:
header {
position: relative;
height: 100%;
width: 100%;
background-color: black;
}
This makes it in the size of the browser's viewport, what I did on purpose because I wanted that result. I also had to give the html, body element the CSS property's for this to work (filling the screen with the first element):
html, body {
height: 100%;
width: 100%;
}
The second element I have looks like this:
#content {
display: none;
position: relative;
height: 1500px;
width: 100%;
background-color: yellow;
}
This element is underneath the first one.
As you can see, this element is hidden. That's because when I click on the button on the first element (which you can see in the jsFiddle) it shows the #content element, scrolls to that, and hides the element where we came from (header) when it's done scrolling.
Which works perfectly, I've got the function here:
var showScrollHide = function(showTime, element, eleTime, hide, hideTime, func) {
var _ele = $(element),
_hide = $(hide);
_ele.fadeIn(showTime, function() {
$('html, body').animate({
scrollTop: _ele.offset().top
}, eleTime, function() {
_hide.fadeOut(hideTime, func ? func : null);
});
});
};
I'm calling that function by this piece of code:
$('.exploreBtn').on('click', function() {
showScrollHide(500, content, 1000, header, 250, function() {
$(window).scrollTop(0);
$('.scrollBackBtn').fadeIn();
});
});
In the snippet above I had to call $(window).scrollTop(0); otherwise it would scroll down the page a bit when it was done scrolling. Also I displayed the scroll back button now, but that is the problem.
When I'm on the second element, and the element above it is hidden by the function above. And I try to use the same function to scroll it back up which means:
Show the element above
Scroll to it
Fade out the element we came from
It only gives me a fade to the element I'm trying to scroll to.
When I removed all the code from the function, and only used this:
$('header').fadeIn();
It just did the same and automatically faded the screen to that element we have just faded in. Which means it scrolls up, but not with any animation or what so ever.
Here is a jsFiddle to show what I'm doing
Btw, I already fixed this issue with the help of #Loktar with this piece of code, but I'm still not sure if its the right way to do it:
$('.scrollBackBtn').on('click', function() {
$(window).scrollTop(0);
$(header).slideDown();
});
If I am understanding it correctly the following should work.
_scrollBackBtn.on('click', function() {
_window.scrollTop(0);
$(header).slideDown();
});
Live Demo

Jquery, slideup() but do not remove element

I've got an app that looks like a Windows desktop. There are icons that open draggable windows (divs) which display the content.
When I close a window, this happens:
$('#element'+boxId).animate({height: 0, opacity: 0}, 'fast');
When I open a window, this happens
$('#element'+boxId).slideDown();
Problem is, once a window is closed, I cannot reopen it. If I want to see that window again I have to refresh the page and then open it.
Is there some way to do a cool fade out that does not completely remove the element?
I have also tried regular old slideUp() but that does the same thing.
This works fine, just not as cool looking.
document.getElementById('element'+boxId).style.display = "none";
The problem is that you are hiding it by affecting the height and opacity, and those aren't being reset by the slideDown. Here's one option:
http://jsfiddle.net/uggVb/
$('#hide').click(function (e) {
e.preventDefault();
var $div = $('#theDiv');
$div.data('originalHeight', $div.css('height'));
$('#theDiv').animate({
height: 0,
opacity: 0
}, 'fast');
//$('#theDiv').slideUp('fast');
});
$('#show').click(function (e) {
e.preventDefault();
$('#theDiv').animate({
height: $('#theDiv').data('originalHeight'),
opacity: 1
}, 'fast');
//$('#theDiv').slideDown('fast');
});
You could use the slide functions instead of the animate functions, either work.
How about only using jQuery to add and remove a hide class and use CSS transitions for the properties you want to animate?
jQuery:
$('#whatever').click(function(ev) {
var $el = $('#element' + boxId);
$el.toggleClass('hide');
});
CSS:
#element { /* or #element{{boxId}} or some class added to those elements */
opacity: 1;
overflow: hidden;
width: 100px; height: 100px;
transition: height 300ms, opacity 300ms;
}
#element.hide {
opacity: 0;
height: 0;
}
See demo
Not sure if it is what you want but you can look into jQuery hide/show functions
$('#element'+boxId).hide();
if you want slower/faster animation you can give hide parameter which represents animation speed(in miliseconds)
$('#element'+boxId).hide(1000);

Scroll event background change

I am trying to add a scroll event which will change the background of a div which also acts as the window background (it has 100% width and height). This is as far as I get. I am not so good at jquery. I have seen tutorials with click event listeners. but applying the same concept , like, returning scroll event as false, gets me nowhere. also I saw a tutorial on SO where the person suggest use of array. but I get pretty confused using arrays (mostly due to syntax).
I know about plugins like waypoints.js and skrollr.js which can be used but I need to change around 50-60 (for the illusion of a video being played when scrolled) ... but it wont be feasible.
here is the code im using:-
*
{
border: 2px solid black;
}
#frame
{
background: url('1.jpg') no-repeat;
height: 1000px;
width: 100%;
}
</style>
<script>
$(function(){
for ( i=0; i = $.scrolltop; i++)
{
$("#frame").attr('src', ''+i+'.jpg');
}
});
</script>
<body>
<div id="frame"></div>
</body>
Inside your for loop, you are setting the src attribute of #frame but it is a div not an img.
So, instead of this:
$("#frame").attr('src', ''+i+'.jpg');
Try this:
$("#frame").css('background-image', 'url(' + i + '.jpg)');
To bind a scroll event to a target element with jQuery:
$('#target').scroll(function() {
//do stuff here
});
To bind a scroll event to the window with jQuery:
$(window).scroll(function () {
//do stuff here
});
Here is the documentation for jQuery .scroll().
UPDATE:
If I understand right, here is a working demo on jsFiddle of what you want to achieve.
CSS:
html, body {
min-height: 1200px; /* for testing the scroll bar */
}
div#frame {
display: block;
position: fixed; /* Set this to fixed to lock that element on the position */
width: 300px;
height: 300px;
z-index: -1; /* Keep the bg frame at the bottom of other elements. */
}
Javascript:
$(document).ready(function() {
switchImage();
});
$(window).scroll(function () {
switchImage();
});
//using images from dummyimages.com for demonstration (300px by 300px)
var images = ["http://dummyimage.com/300x300/000000/fff",
"http://dummyimage.com/300x300/ffcc00/000",
"http://dummyimage.com/300x300/ff0000/000",
"http://dummyimage.com/300x300/ff00cc/000",
"http://dummyimage.com/300x300/ccff00/000"
];
//Gets a valid index from the image array using the scroll-y value as a factor.
function switchImage()
{
var sTop = $(window).scrollTop();
var index = sTop > 0 ? $(document).height() / sTop : 0;
index = Math.round(index) % images.length;
//console.log(index);
$("#frame").css('background-image', 'url(' + images[index] + ')');
}
HTML:
<div id="frame"></div>
Further Suggestions:
I suggest you change the background-image of the body, instead of the div. But, if you have to use a div for this; then you better add a resize event-istener to the window and set/update the height of that div with every resize. The reason is; height:100% does not work as expected in any browser.
I've done this before myself and if I were you I wouldn't use the image as a background, instead use a normal "img" tag prepend it to the top of your page use some css to ensure it stays in the back under all of the other elements. This way you could manipulate the size of the image to fit screen width better. I ran into a lot of issues trying to get the background to size correctly.
Html markup:
<body>
<img src="1.jpg" id="img" />
</body>
Script code:
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200) {
// function goes here
$('img').attr('src', ++count +'.jpg');
}
});
});
I'm not totally sure if this is what you're trying to do but basically, when the window is scrolled, you assign the value of the distance to the top of the page, then you can run an if statement to see if you are a certain point. After that just simply change run the function you would like to run.
If you want to supply a range you want the image to change from do something like this, so what will happen is this will allow you to run a function only between the specificied range between 200 and 400 which is the distance from the top of the page.
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200 && topPage < 400) {
// function goes here
$('#img').attr('src', ++count +'.jpg');
}
});
});

Categories

Resources