Nav bar appearing and disappearing on scroll - javascript

So I am trying to make a nav bar which is hidden when you first load the page and displays when you scroll down to the second section, I have got it working but when you scroll up and down within the home section, the nav bar keeps appearing and disappearing again when it should stay out of sight.
Live Demo: http://zimxtrial.ukbigbuy.com/
JS:
<script type="text/javascript">
jQuery(document).ready(function() {
var startY= jQuery('#home').position().top + jQuery('#home').outerHeight();
jQuery('#nav-container').html( jQuery('#nav').html());
jQuery(window).scroll(function () {
if(jQuery(this).scrollTop() > startY ){
jQuery('#nav-container').slideDown();
}else{
$('#nav-container').css({display: 'block'});
jQuery('#nav-container').slideUp();
}
});
});
</script>
CSS:
#nav-container {
position: fixed;
height: 50px;
width: 100%;
min-width: 600px;
display: none;
}
Any help would be greatly appreciated, thanks guys.
Also, this is my first time messing around with JQuery and JS so be kind.
Final version after fix:
<script type="text/javascript">
$(document).ready(function() {
var startY= $('#home').position().top + $('#home').outerHeight();
var navc = $('#nav-container')
navc.html( $('#nav').html());
$(window).scroll(function () {
if($(this).scrollTop() > startY ){
navc.slideDown();
}else{
navc.slideUp();
}
});
});
</script>

Because you are inside the .scroll() function which gets fired everytime the page is scrolled, it will be going to your else condition and displaying the navbar each time because of this line:
$('#nav-container').css({display: 'block'});
Remove this line and it should work as expected.

You would need to check if the navBar is show or not and depending on that run the scroll() function only if the state is the correct one. Something like this:
if(jQuery(this).scrollTop() > startY && $("#nav-container").css('display') == "none" ){
jQuery('#nav-container').slideDown();
}else if( && $("#nav-container").css('display') == "block"){
$('#nav-container').css({display: 'block'});
jQuery('#nav-container').slideUp();
}

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.

Element visible betwen scroll points

I have some element that is visible when scroll is bigger than 890px.
But i have problem that element has to be visible between 890px and 920px, and if user scroll more thna 920 or less than 890px i need to hide that element.
I am using animated css for adding animation to element when appear.
This is what i have for now in JS
var $document = $(document),
$elementField = $('.center-field');
$document.scroll(function () {
if ($document.scrollTop() >= 890) {
$elementField.stop().addClass("show animated bounceInDown");
}
});
Now it will appear when user scroll more than 890px, but when user goes back it will stay again, is there somekind of watch user scroll?
Just be a bit more specific with the if condition.
var $document = $(document),
$elementField = $('.center-field');
$document.scroll(function () {
if ($document.scrollTop() >= 890 && $document.scrollTop() <= 920) {
$elementField.css('color', 'tomato');
} else {
$elementField.css('color', 'blue');
}
});
body {
position: relative;
height:1800px;
}
.center-field {
position: absolute;
top: 900px;
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>scroll down please</p>
<h1 class="center-field">Hello</h1>
The code you done is working like that:
every time you scroll:
check if the scroll is more than 890px
if so add the class
As you can see it doesn't contains the logic of hiding the element.
You need to check if the scroll is less than 890px and remove the classes.
You can try something like that (assuming that when you node hasn't the class show it is hidden):
var $document = $(document),
$elementField = $('.center-field');
$document.scroll(function () {
var scroll = $document.scrollTop();
if (scroll >= 890 && scroll <= 920) {
$elementField.addClass("show animated bounceInDown").removeClass("fadeOut");
} else {
$elementField.removeClass("show bounceInDown").addClass("fadeOut");
}
});
Cant you do a hide in the else?
$document.scroll(function () {
if ($document.scrollTop() >= 890) {
$elementField.stop().addClass("show animated bounceInDown");
}else{
$elementField.hide(); //or something like that
}

Making a nav bar revert to normal after scrolling to top of page

So i'm trying to learn javascript and jQuery. I was coding a project website and wanted to make the nav smaller and transparent as they scroll around the page. i wrote this and it works fine `
$(document).scroll(function(){
$('.nav').css({"opacity": "0.85", "height": "55px"});
$('.nav-container').css({"margin-top": "-13px", "font-size": "1.4em"})
});
`
But i want it to revert back to normal when they scroll all the way to the top. There doesn't seem to be a jQuery event for this.
I'd personally suggest:
$(document).scroll(function () {
// select the relevant elements:
$('#nav, .nav-container')[
// if the window is at the 'top', we use the 'removeClass' method,
// otherwise we use 'addClass':
$(window).scrollTop() == 0 ? 'removeClass' : 'addClass'
// and pass the 'scrolled' class-name to the method:
]('scrolled');
});
With the CSS:
.nav.scrolled {
opacity: 0.85;
height: 55px;
}
.nav-container.scrolled {
margin-top: -13px;
font-size: 1.4em;
}
JS Fiddle demo.
This also uses corrected (valid HTML).
References:
addClass().
removeClass().
scroll().
I have updated your jsfiddle here
I just changed your .scroll() function:
$(document).scroll(function () {
var scroll = $(this).scrollTop();
if(scroll > 0){
$('.nav').addClass('scrolled');
$('.nav-container').addClass('scrolled');
} else if(scroll == 0){
$('.nav').removeClass('scrolled');
$('.nav-container').removeClass('scrolled');
}
});
and added this css:
.nav.scrolled {
opacity:0.85;
height:55px;
}
.nav-container.scrolled {
margin-top:-13px;
font-size:1.4em;
}

How to make text appear on scroll in html

Hello, I want a certain text to appear when I scroll past it or when I scroll until the point where the text is. The effect when appearing should be somewhat like the first effect on the top of the website http://namanyayg.com/.
I want the effect in minimal code with pure CSS and JS i.e no jQuery.
I was thinking that maybe I would use something like a display:none property for a span and then when you scroll past it the display becomes block but I dont know how to trigger the effect using javascript.
Any help would be appreciated.
First wrap whatever your text or content that you want to show on scroll, in one div so that you can show hide the div depending upon the scroll. Write two classes for your target div.
Your CSS:
/*Use this class when you want your content to be hidden*/
.BeforeScroll
{
height: 100px; /*Whatever you want*/
width: 100%; /*Whatever you want*/
.
.
display: none;
}
/*Use this class when you want your content to be shown after some scroll*/
.AfterScroll
{
height: 100px; /*Whatever you want*/
width: 100%; /*Whatever you want*/
.
.
display: block;
}
Your HTML:
<!--Set class BeforeScoll to your target div-->
<div id = "divToShowHide" class = "BeforeScroll">Content you want to show hide on scroll</div>
Your Script:
<!--include these script in head section or wherever you want-->
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js" type="text/javascript"></script>
<script type = "text/javascript">
$(document).ready(function(){
//Take your div into one js variable
var div = $("#divToShowHide");
//Take the current position (vertical position from top) of your div in the variable
var pos = div.position();
//Now when scroll event trigger do following
$(window).scroll(function () {
var windowpos = $(window).scrollTop();
//Now if you scroll more than 100 pixels vertically change the class to AfterScroll
// I am taking 100px scroll, you can take whatever you need
if (windowpos >= (pos.top - 100)) {
div.addClass("AfterScroll");
}
//If scroll is less than 100px, remove the class AfterScroll so that your content will be hidden again
else {
s.removeClass("AfterScroll");
}
//Note: If you want the content should be shown always once you scroll and do not want to hide it again when go to top agian, no need to write the else part
});
});
</script>
Hope it will solve your problem.
I would recommend this plugin
http://johnpolacek.github.io/superscrollorama/
Edit:
I don't know how no one noticed that the solution had to be made without using external libraries like jQuery. However, the solution is extremely easy with basic functionality. Find it here
HTML:
<div id="parent-div">
<div id="child-div">
Psst .. I am here!!
</div>
</div>
CSS:
#parent-div
{
position:relative;
height:3000px;
width:300px;
background-color:red;
}
#child-div
{
color:white;
position:relative;
top:1000px;
width:300px;
display:none;
text-align:center;
}
JS:
var body=document.getElementsByTagName("body")[0];
var parent=document.getElementById("parent-div");
var child=document.getElementById("child-div");
body.onscroll = function(){
//console.log(documenhttps://fiddle.jshell.net/3urv0tp0/#tidyt.getElementById("child-div").style.top)
if(document.documentElement.scrollTop>=child.offsetTop)//Adjust Tolerance as you want
{
child.style.display="block"
}
};
I was looking for this either. Here i was trying to make "show text after scrolling to (number)px with fade effect". I wish it will work as it works for me :) The animation will be playing again if u scroll back to it, idk how to make it just one like in web u showed xd (i will edit if I find out)
window.addEventListener("scroll", function() {showFunction()});
function showFunction() {
if (document.body.scrollTop > 900 || document.documentElement.scrollTop > 900) {
document.getElementById("toptexts2").style.display = "block";
} else {
document.getElementById("toptexts2").style.display = "none";
}
}
.toptexts2 {
animation: fadeEffect 3s; /* fading effect takes 3s */
}
#keyframes fadeEffect { /* from 0 to full opacity */
from {opacity: 0;}
to {opacity: 1;}
}
<div class="toptexts2" id="toptexts2">
<div>Hi!</div>
<div>↓ go down ↓</div>
</div>
I like this:
var doc = document, dE = doc.documentElement, bod = doc.body;
function E(e){
return doc.getElementById(e);
}
function xy(e, d){
if(!d)d = 'Top';
d = 'offset'+d;
var r = e[d];
while(e.offsetParent){
e = e.offsetParent; r += e[d];
}
return r;
}
function x(e){
return xy(e, 'Left');
}
function y(e){
return xy(e);
}
var txt = E('theId'), txtS = txt.style;
onscroll = function(){
var left = dE.scrollLeft || bod.scrollLeft || 0;
var top = dE.scrollTop || bod.scrollTop || 0;
var w = innerWidth || dE.clientWidth || bod.clientWidth;
var h = innerHeight || dE.clientHeight || bod.clientHeight;
if(top > y(txt)-h){
txtS.display = 'none';
}
else{
txtS.display = 'block';
}
}
I left the left stuff in there, just in case, but you can probably remove it.
var div=$("#divtochange");
$(window).scroll(function () {
var windowpos = $(window).scrollTop();
//---check the console to acurately see what the positions you need---
console.log(windowpos);
//---------------------
//Enter the band you want the div to be displayed
if ((windowpos >= 0) && (windowpos <= 114)){
div.addClass("AfterScroll");
}
else{
div.removeClass("AfterScroll");
}

dealing with sliding in jquery?

i have this script that with li list, if you click on one of the list items, a box slides to the right, and if you click again, its slides back to its orginal place(toggle)
the demo is here:
http://www.kornar.co.uk/home2.php
the problem that i have is on slideout, i want the width of the panel to be 700px
$(".panel").css("width","700px");
on slide back in, i want the width to be 350px, so it hides behind the list again.
$(".panel").css("width","350px");
but the problem im having is on when it slides back, it deosnt hide behind the list, it still shows the panel on the right? thanks
Hey dude, I made a couple of assumptions about what you were trying achieve on the whole, but maybe this is what you were trying to do... The following is all I changed:
<script type="text/javascript">
$(document).ready(function() {
$('.block').click(function(){
var id= $(this).attr('id');
var data_id= $(".data").html();
var panelPositionLeft=$('.panel').css('left');
if(panelPositionLeft=='0px') {
//the .panel is hidden, so slide it out and populate .data with the new id
$('.panel').animate({left: 350, width:700});
$('.data').html(id);
} else if (data_id!=id){
//something other than the previous .block was clicked and the .panel is obviously open, so don't collapse, just add the new id into .data
$('.data').html(id);
} else {
//neither of the previous situations are true, so it must be that the previously clicked block is being clicked again. Just slide it closed and don't change the value of .data
$('.panel').animate({left: 0, width: 350});
}
});
$('.close').click(function(){
// just slide it closed.
$('.panel').animate({left: 0, width: 350});
});
});
</script>
There are still a few things you could clean up, but I thought this would be a little easier to read and understand. Try this out, let me know if I misunderstood the problem.
Thanks!
Try surrounding the "+" with quotes (i.e. "+" + panel.outerWidth()). I think this should work.
Richard
For getaways reference: this is what I would have posted had masondesu not got there first. As you can see it is very similar, but has if statements where none are actually required (as in masondesu's solution.
$(document).ready(function () {
$('.block').click(function () {
var id = $(this).attr('id');
var data_id = $(".data").html();
var panel = $('.panel');
var panel_width = $('.panel').css('left');
var currLeft = panel.css('left');
var blockWidth = $(".left").outerWidth();
if (data_id == id) {
if (currLeft == "0px") {
panel.animate({ left: blockWidth, width: "700px" });
} else {
panel.animate({ left: "0px", width: "350px" });
}
}
else {
if (currLeft == "0px") {
panel.animate({ left: blockWidth, width: "700px" });
} else {
panel.animate({ left: "0px", width: "350px" });
}
}
$('.data').html(id);
return false;
});
$('.close').click(function () {
var panel = $('.panel');
var currLeft = panel.css('left');
if (currLeft == "0px") {
panel.animate({ left: blockWidth, width: "700px" });
} else {
panel.animate({ left: "0px", width: "350px" });
}
return false;
});
});
Regards,
Richard
You don't resize the panel on "li"-click, it resizes only on ".close"-click. so it won't resize ;)

Categories

Resources