javascript not hiding element when opening webpage - javascript

jQuery(window).scroll( function(){
/* Check the location of element */
jQuery('.logoscrollbg').each( function(i){
var logo = jQuery(this).outerHeight();
var position = jQuery(window).scrollTop();
/* fade out */
if( position > logo ){
jQuery(this).animate({'opacity':'1'},100);
}else{ jQuery(this).animate({'opacity':'0'},100);}
});
});
Above is my script for a class (the header) with should blend in when the page is being scrolled down and blend out when you are on the top of the page, with other words the start.
I don't understand javascript at all, but I do a little php and I was wondering if someone could help me write there a elseif tag and later make the else tag so that is the page is loaded the class(.logoscrollbg) isn't visible and when u start scrolling it gets visible and when you get to the top it gets invisivle again :)
The script works like this right now: when I enter the site it shows the bar(bad), later when scrolling it stays or well is there(good), then when getting to top again it fades out(good).

The code inside your scroll event needs to be run when the page is loaded as well as when it scrolls.
jQuery(function() {
// object to hold our method
var scrollCheck = {};
// define and call our method at once
(scrollCheck.check = function() {
// only need to get scrollTop once
var logo, position = jQuery(window).scrollTop();
/* Check the location of element */
jQuery('.logoscrollbg').each(function() {
logo = jQuery(this).outerHeight();
/* fade out or in */
// cleaned this up a bit
jQuery(this).animate({'opacity': position > logo ? 1 : 0}, 100);
});
})();
jQuery(window).scroll(function(){
// call our method
scrollCheck.check();
});
});

It looks to me like this will only fire when you scroll. Try updating your js to this:
jQuery(window).on('scroll, load', function() {
/* Check the location of element */
jQuery('.logoscrollbg').each( function(i){
var logo = jQuery(this).outerHeight();
var position = jQuery(window).scrollTop();
/* fade out */
if( position > logo ){
jQuery(this).animate({'opacity':'1'},100);
}else{ jQuery(this).animate({'opacity':'0'},100);}
});
});
*note: You may want to fire the callback on document load instead of window.

Related

Sticky navigation bar doesn't work properly

I'm using this code to make the navigation bar stick to the top of the page after scrolling:
var nav=$('body');
var scrolled=false;
$(window).scroll(function(){
if(175<$(window).scrollTop()&&!scrolled){
nav.addClass('stuck');
$('.navigation-class').animate({marginTop:80},1000);
scrolled=true;
}
if(175>$(window).scrollTop()&&scrolled){
$('.navigation-class').animate({marginTop:0},0,function(){nav.removeClass('stuck');$('.navigation-class').removeAttr('style');});
scrolled=false;
}
});
The problem is, if the user scrolls the page up and down quickly, and the navigation is STILL animating, it will continue the animation and then suddenly jump into it's designed position, which gives a hiccup effect to the menu.
Try to scroll this page quickly to see it in live.
Is it possible to make it run smoothly like other websites?
Thanks are in order.
Edit:
After rereading the question, I realized the problem is probably that you're not cancelling the animation when the user scrolls back above 175px.
Presumably you're applying position: float to your nav element? Are you removing float as soon as the user scrolls up?
Try setting the queue option to false (see https://api.jquery.com/animate/), so the animation doesn't wait for the other one to complete.
Maybe you could try getting rid of the JQuery animation and replacing it with CSS transitions?
Maybe something like this?
var nav=$('body');
var scrolled=false;
var scrollToggle = function(){
$(window).off('scroll');
if(175<$(window).scrollTop()&&!scrolled){
nav.addClass('stuck');
$('.navigation-class').animate({marginTop:80},1000, function() {
$(window).on('scroll', scrollToggle);
);
scrolled=true;
}
else if(175>$(window).scrollTop()&&scrolled){
$('.navigation-class').animate({marginTop:0},0,function({
nav.removeClass('stuck');
$('.navigation-class').removeAttr('style');
$(window).on('scroll', scrollToggle);
});
scrolled=false;
}
};
$(window).on('scroll', scrollToggle);
I have something similar in a WIP myself. I'll post it here only slightly edited, maybe it can be useful to you.
var headerFloat = function() {
//Header
var pageHeader = $('#pageHeader'), pos = '',
headerMain = $('#headerMain'), headerMainHeight = '',
content = $('#content'), contentPadding = '',
pageTitle = $('h1.currentPage'), pageTitleTop = '';
if($(window).scrollTop() >= 95) {
pos = "fixed";
headerMainHeight = '75px';
contentPadding = '225px';
pageTitleTop = '55px';
contentHeaderTop = '130px';
}
//Header
pageHeader.css('position', pos);
headerMain.css('height', headerMainHeight);
content.css('padding-top', contentPadding);
pageTitle.css({ 'transition': 'all 0s', 'position': pos, 'top': pageTitleTop });
pageTitle[0].offsetHeight; //force "reflow" of element -- stackoverflow.com/questions/11131875/#16575811
pageTitle.css('transition', '');
};
$(document).ready(function() {
/* *** SCROLL -> FLOAT HEADER *** */
$(window).on("scroll.float", headerFloat);
});
Inputting '' (empty string) in the JQuery css function resets it to the original value. You should do that instead of .removeAttr('style');
I would also avoid the scrolled boolean. I think you need it anyway, if scrollTop < 175, you'll never be scrolled, and vice versa.

Auto-scroll embedded window only once when entering viewport. Can't scroll back up

I have an image embedded in a container with a background image to give the effect of scrolling within the page. Initially, I had the scrolling effect take place on page load, with this simple bit of script which worked perfectly.
$(window).on("load", function () {
$(".embedded_scroller_image").animate({ scrollTop: $('.embedded_scroller_image')[0].scrollHeight}, 2500, "easeInOutCubic");
}); // end on load
However, the element is too far down the page now and I want that animation to fire when the element enters 80% of the viewport. That part is also working fine with this code here (I'm using a scroll limiter to improve browser performance)
// limit scroll call for performance
var scrollHandling = {
allow: true,
reallow: function() {
scrollHandling.allow = true;
},
delay: 500 //(milliseconds) adjust to the highest acceptable value
};
$(window).on('scroll', function() {
var flag = true;
if(scrollHandling.allow) { // call scroll limit
var inViewport = $(window).height()*0.8; // get 80% of viewport
$('.embedded_scroller_image').each(function() { // check each embedded scroller
var distance = $(this).offset().top - inViewport; // check when it reaches offset
if ($(window).scrollTop() >= distance && flag === true ) {
$(this).animate({ scrollTop: $(this)[0].scrollHeight}, 2500, "easeInOutCubic"); //animate embedded scroller
flag = false;
}
});
} // end scroll limit
}); // end window scroll function
The problem is this: I want the autoscroll to happen once and then stop. Right now, it works on entering viewport, but if I then try to manually scroll the image, it keeps pushing back down or stutters. You can't get the element to scroll normally. I attempted to use the flag in the code to stop the animation, but couldn't get that to successfully work.
How can I have this animation fire when the element is 80% in the viewport, but then completely stop after one time?
Here is a codepen I mocked up as well http://codepen.io/jphogan/pen/PPQwZL?editors=001 If you scroll down, you will see the image element autoscroll when it enters the viewport, but if you try to then scroll that image up in its container, it won't work.
Thanks!
I have tweaked your script a bit:
// limit scroll call for performance
var scrollHandling = {
allow: true,
reallow: function() { scrollHandling.allow = true; },
delay: 500 //(milliseconds) adjust to the highest acceptable value
};
$(window).on('scroll', function() {
if(scrollHandling.allow) { // call scroll limit
var inViewport = $(window).height()*0.8; // get 80% of viewport
$('.embedded_scroller_image').each(function() { // check each embedded scroller
var distance = $(this).offset().top - inViewport; // check when it reaches offset
if ($(window).scrollTop() >= distance ) {
$(this).animate({ scrollTop: $(this)[0].scrollHeight}, 2500, "easeInOutCubic"); //animate embedded scroller
scrollHandling.allow = false;
}
});
} // end scroll limit
}); // end window scroll function
I have kicked out your flag and simply made use of scrollHandling.allow declared already.
Try if it works for you :)
Cheers!

jquery responsive wordpress slider height change

I have a premium wordpress theme which came with a built in full page slider. It integrates nicely into my website but it displays full page and the information underneath is being lost. The slider is responsive to the window size, I'd like it to be only 60%. Please can someone help:
(function ($) {
"use strict";
$.fn.maximage = function (settings, helperSettings) {
var config;
if (typeof settings == 'object' || settings === undefined) config = $.extend( $.fn.maximage.defaults, settings || {} );
if (typeof settings == 'string') config = $.fn.maximage.defaults;
/*jslint browser: true*/
$.Body = $('body');
$.Window = $(window);
$.Scroll = $('html, body');
$.Events = {
RESIZE: 'resize'
};
this.each(function() {
var $self = $(this),
preload_count = 0,
imageCache = [];
/* --------------------- */
// #Modern
/*
MODERN BROWSER NOTES:
Modern browsers have CSS3 background-size option so we setup the DOM to be the following structure for cycle plugin:
div = cycle
div = slide with background-size:cover
div = slide with background-size:cover
etc.
*/
var Modern = {
setup: function(){
if($.Slides.length > 0){
// Setup images
for(var i in $.Slides) {
// Set our image
var $img = $.Slides[i];
// Create a div with a background image so we can use CSS3's position cover (for modern browsers)
$self.append('<div class="mc-image ' + $img.theclass + '" title="' + $img.alt + '" style="background-image:url(\'' + $img.url + '\');' + $img.style + '" data-href="'+ $img.datahref +'">'+ $img.content +'</div>');
}
// Begin our preload process (increments itself after load)
Modern.preload(0);
// If using Cycle, this resets the height and width of each div to always fill the window; otherwise can be done with CSS
Modern.resize();
}
},
preload: function(n){
// Preload all of the images but never show them, just use their completion so we know that they are done
// and so that the browser can cache them / fade them in smoothly
// Create new image object
var $img = $('<img/>');
$img.load(function() {
// Once the first image has completed loading, start the slideshow, etc.
if(preload_count==0) {
// Only start cycle after first image has loaded
Cycle.setup();
// Run user defined onFirstImageLoaded() function
config.onFirstImageLoaded();
}
// preload_count starts with 0, $.Slides.length starts with 1
if(preload_count==($.Slides.length-1)) {
// If we have just loaded the final image, run the user defined function onImagesLoaded()
config.onImagesLoaded( $self );
}else{
// Increment the counter
preload_count++;
// Load the next image
Modern.preload(preload_count);
}
});
// Set the src... this triggers begin of load
$img[0].src = $.Slides[n].url;
// Push to external array to avoid cleanup by aggressive garbage collectors
imageCache.push($img[0]);
},
resize: function(){
// Cycle sets the height of each slide so when we resize our browser window this becomes a problem.
// - the cycle option 'slideResize' has to be set to false otherwise it will trump our resize
$.Window
.bind($.Events.RESIZE,
function(){
// Remove scrollbars so we can take propper measurements
$.Scroll.addClass('mc-hide-scrolls');
// Set vars so we don't have to constantly check it
$.Window
.data('h', Utils.sizes().h)
.data('w', Utils.sizes().w);
// Set container and slides height and width to match the window size
$self
.height($.Window.data('h')).width($.Window.data('w'))
.children()
.height($.Window.data('h')).width($.Window.data('w'));
// This is special noise for cycle (cycle has separate height and width for each slide)
$self.children().each(function(){
this.cycleH = $.Window.data('h');
this.cycleW = $.Window.data('w');
});
// Put the scrollbars back to how they were
$($.Scroll).removeClass('mc-hide-scrolls');
});
}
}
Thanks in advance. James
Generally, the themes are very customizable on the admin panel. So, you should check it out before you changing it by hand.
If you dont find for customization on the admin panel (and on the theme developer page), as you may be know, when the themes are responsive they are using some framework like bootstrap, foundation, whatever. And then, the slider have to have a css class like "large-12", it should be modified to change its size, for example "large-8", then the slider size will be 8/12.
I hope it help you!

jQuery hover animations based on viewport size

in the process of learning more jQuery and have an issue with some code.
I am attempting to have an animation effect (fadeIn/fadeOut) when the user hovers over a specific element.
However, when the viewport is resized, ie below 480px for mobile display, I need the hover effects to be ignored and just display the call to action. In my code below I am trying to detect the viewport and then apply the appropriate script through an if-then-else statement.
I suspect that I'm not nesting something properly or have a misplaced semi-colon. I've been staring at this a while and am stuck.
I did look at these other posts as reference.
http://j.mp/1hejP0B
http://j.mp/1hejRFK
Let me know if you have any questions or can provide additional details.
// Script to display div call-to-action over logos
var detectViewPort = function(){
var viewPortWidth = $(window).width();
// if its bigger than 480px then do the hover effect
if (viewPortWidth > 480){
// On mouse over logo
$('.unionlogo').hover(function() {
// Display the call to action
$(this).find('a.calltoaction').stop(false,true).fadeIn(400);
$(this).find('p.union-name').stop(false,true).fadeOut(400);
},
function() {
// Hide the call to action
$(this).find('a.calltoaction').stop(false,true).fadeOut(400);
$(this).find('p.union-name').stop(false,true).fadeIn(400);
});
// if its smaller than 480px then just show the call-to-action
}else{
$('a.calltoaction').show();
};
$(function(){
detectViewPort();
});
$(window).resize(function () {
detectViewPort();
});
Did you look in your console to see what the error message was? As you said, you left off a bracket. You should be formatting your code a little better, and it would have been obvious.
var detectViewPort = function(){
var viewPortWidth = $(window).width();
// if its bigger than 480px then do the hover effect
if (viewPortWidth > 480){
$('a.calltoaction').hide();
// On mouse over logo
$('.unionlogo').off('mouseenter mouseleave');
$('.unionlogo').hover(function() {
// Display the call to action
$(this).find('a.calltoaction').stop(false, true).fadeIn(400);
$(this).find('p.union-name').stop(false, true).fadeOut(400);
}, function() {
// Hide the call to action
$(this).find('a.calltoaction').stop(false, true).fadeOut(400);
$(this).find('p.union-name').stop(false, true).fadeIn(400);
});
// if its smaller than 480px then just show the call-to-action
} else {
$('.unionlogo a.calltoaction').stop(false,true).fadeOut(400);
$('.unionlogo p.union-name').stop(false,true).fadeIn(400);
$('a.calltoaction').show();
// un bind the hover incase of browser resize
$('.unionlogo').off('mouseenter mouseleave');
};
}
$(function(){
$(document).ready(function(){
detectViewPort();
});
});
$(window).resize(function () {
detectViewPort();
});
Maybe try adding a media query to the CSS to hide the original button and add a call to action button when the view port is 480px or less.

js smooth stick navigation

I have a question but I actually do not know how to ask.
I am trying to make a navigation bar stick on top when pass a point smoothly.
My reference is this -> http://blog.yjl.im/2010/01/stick-div-at-top-after-scrolling.html
My problem is when I use IE or Chrome to check it, there is a "blink" effect.
It is more like the scroll function will finish process after scroll over the point. So the things(HTML) after Nav will go on the top of the Nav on 0.1 ~ 0.3 secs then scroll function will finish process. Even through is short but it is visualize-able when the HTML over the nav.
However, If I use Firefox to check it, there is no such blink effect.....
May I ask what is the problem here I got?? What Should I check about??
My setting is a Anchor right before the Nav, Nav z-index = 99, and inside of the scroll function is below.
$(this).scrollTop() > $(anchor).offset().top
? nav.addClass('sticky')
: nav.removeClass('sticky')
jQuery(document).ready(function($) {
var my_nav = $('.navbar-sticky');
// grab the initial top offset of the navigation
var sticky_navigation_offset_top = my_nav.offset().top;
// our function that decides weather the navigation bar should have "fixed" css position or not.
var sticky_navigation = function(){
var scroll_top = $(window).scrollTop(); // our current vertical position from the top
// if we've scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative
if (scroll_top > sticky_navigation_offset_top) {
my_nav.addClass( 'stick' );
} else {
my_nav.removeClass( 'stick' );
}
};
var initio_parallax_animation = function() {
$('.parallax').each( function(i, obj) {
var speed = $(this).attr('parallax-speed');
if( speed ) {
var background_pos = '-' + (window.pageYOffset / speed) + "px";
$(this).css( 'background-position', 'center ' + background_pos );
}
});
}
// run our function on load
sticky_navigation();
// and run it again every time you scroll
$(window).scroll(function() {
sticky_navigation();
initio_parallax_animation();
});
});

Categories