I recently repurposed a template for http://c42d.com, a portfolio website I'm building for a company called C42D. My issue concerns the scrolling functionality of the navigation system.
It works properly on the homepage. When you click any link in the nav at the top, it scrolls right to that section on the page perfectly, and it takes into consideration the height of the fixed header. The following Javascript is responsible for this functionality:
/** Hash Scroll */
/** Portfolio Filter */
$( '#navbar-spy' ).off( 'click' ).on( 'click', 'a', function( e ) {
if(!$( this ).attr( 'href' ).match(/^#/)) return;
e.preventDefault();
var elmHash = $( this ).attr( 'href' );
var elmOffsetTop = Math.ceil( $( this.hash ).offset().top );
var windowOffsetTop = Math.ceil( $(window).scrollTop() );
if( elmOffsetTop != 0 ) {
elmOffsetTop = elmOffsetTop - 84;
if( windowOffsetTop == 0 ) {
elmOffsetTop = elmOffsetTop - 0;
}
}
//console.log( $( this ).attr( 'href' ) );
$( 'html:not(:animated), body:not(:animated)' ).animate({ scrollTop: elmOffsetTop }, 1100 );
});
Unfortunately, when you navigate to any interior page on the site (http://c42d.com/termsandconditions, for example) and click a link in the nav, it brings you right to the proper anchor on the homepage, but doesn't take into consideration the height of the fixed header, and the title becomes partly obscured.
Any help would be greatly appreciated.
Thank you!
Zan
What I would do is on page load, detect the hash if any, and if there is, then run that same animation code to go to that.
Related
I'm doing a website for desktop and mobile as well, the menu works perfect on desktop but not working on mobile, because I want the smothly scroll to id I use this code:
I found out that event.preventDefault() block a function I turn it off and it transfers me to id, but the animation is disabled at this point
$( 'a[href^="#"]' ).on( 'click', function ( event ) {
var target = $( $( this ).attr( 'href' ) );
var znacznik = $( $( this ).attr( 'a' ) );
if ( target.length ) {
event.preventDefault();
$( 'html, body' ).animate( {
scrollTop: target.offset().top - 80
}, 1000 );
}
} );
Is there any way to make it works on android? Maybe another function then event.preventDefault(); ?
I believe you may be overthinking this one, put an href on the button you want to scroll to, like so:
<button></button>
And for the smooth scrolling all I would do is set your CSS to the following:
html {
scroll-behavior: smooth;
}
Sets the entire page to have animations be smooth between elements.
On my site, I am trying to fix the navigation so that when the browser is getting resized from desktop to mobile size, the mobile menu works. I have the mobile menu working on initial load, and the desktop navigation working on initial load, but when I run the script in a $(window).on('resize', function() {} and click an item as depicted in my script, the event fires always +1 each time the window was rested after a resize.
What I mean is, if I load the page, scale it into mobile size, click the menu and a dropdown item, the click event will fire once. Resize the window out and then back in, the click event will fire now 2 times, then 3, and so on, depending on how many times the browser was resized.
I'm not sure exactly what is going on in my resize script that is screwing everything up and I'm at my wits end at trying to figure it out. Normally people aren't sitting there resizing their browser from desktop to mobile, but my boss does when he show's clients a beta of their site and wants this to never be an issue.
Here is my resize script:
(function( $ ) {
var id,
$body = $('body'),
$window = $( window ),
$navSlider = $('.nav-slider'),
$navMask = $( '.nav-mask' ),
$navToggler = $( '.navbar-toggler' ),
$parent = $( '.menu-item-has-children' ),
$parentLink = $( '.dropdown-toggle' ),
$childContainer = $( '.dropdown-menu' );
$window.on( 'resize', function( e ) {
clearTimeout(id);
id = setTimeout(function() {
close();
var width = $window.width();
if ( width < 992 ) {
setHeightToNav();
$navMask.on( 'click', function() { close() } );
$navToggler.on( 'click', function() { open() } );
$parentLink.on( 'click', function( e ) {
e.preventDefault();
var $this = $( this );
$this.data( 'clicked', true );
console.log( $this.parent() );
} )
}
if ( width >= 992 ) {
resetNavHeight();
console.clear();
}
}, 500 );
} );
function setHeightToNav() {
if ( $body.hasClass( 'logged-in' ) ) {
var $wpAdminBar = $( '#wpadminbar' ).outerHeight();
$navSlider.css( { top: $wpAdminBar + 'px' } );
}
var $navHeight = $( '#header-container' ).outerHeight();
$navSlider.css( { marginTop: $navHeight + 'px' } );
}
function resetNavHeight() {
if ( $body.hasClass( 'logged-in' ) ) {
$navSlider.css( { top: 0 + 'px' } );
}
$navSlider.css( { marginTop: 0 + 'px' } );
}
function close() {
$body.removeClass( 'has-active-menu' );
setTimeout( function() {
$navSlider.removeClass( 'toggling' );
$parent.removeClass( 'show' );
$parentLink.attr( 'aria-expanded', false );
$childContainer.removeClass( 'show' ).removeAttr( 'style' );
$parentLink.data('clicked', false);
}, 250 );
console.log('close()');
}
function open() {
$body.addClass( 'has-active-menu' );
$navSlider.addClass( 'toggling' );
}
})( jQuery );
I've tried my script both with AND without the setTimeout function and it happens exactly the same.
On the project, we are using Bootstrap 4, with the Bootstraps Dropdown._clearMenus(); function commented out in the right places as it was causing conflicts with the functionality I wanted with the navigation.
A link to a site where you can see this is here. It's a WordPress site as well if that matters for anything.
Any help is appreciated. I've been at this for several hours and am at my wits end.
.on( 'click', function ) does not set the event listener, it adds an event listener. Try doing off('click') before setting it if you really need to set this listener here.
But note that any other 'click' listener for this element will also be removed.
That's for the quick fix. You could do better, but that would require more work (track with a boolean if you just changed "display mode", and add or remove the event listeners only then, for example).
I'm using fullpage.js and I'm having a problem with the onloadedmeta function that resizes my background video.
It works perfectly when accessing the page URL directly including the section id with the video. That is to say it resizes to take up the entire screen.
If the section id I'm trying to access is not the section with the background video I see the below error - in this scenario the video resizes correctly but the remaining pages are 144px out from the top (this error fixes itself when I then go to scroll through sections).
Error: Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause().
When I refresh the page using any section id other than the section id that contains the background video the above error is not thrown and the pages resize correctly - but the video does not. The video is just the default size.
I haven't actually noticed this problem previously and some of the aforementioned issues do seem somewhat sporadic. Today I've been created the footer (which contains no JS) and adjusted my mobile menu a little but nothing different to what it was in terms of JS.
I've pasted the JS file below - as you'll see I'm using Fullpage in conjunction with Smoothstate.
If anyone has any suggestions or feedback I'd be eternally grateful.
Thanks very much in advance for your time,
Kind regards
Tom
Edit: all works perfectly if I remove the video from the section
( function( $ ) {
function addFullPage() {
if( $( 'html' ).hasClass( 'fp-enabled' ) ) {
$.fn.fullpage.destroy( 'all' ); // uninitialise fullpage
}
$( '#fullpage' ).fullpage( {
anchors: [ '2d', '3d', 'character','motionandgraphics', 'vfx', 'footer' ],
scrollOverflow: false,
fixedElements: '#masthead',
afterLoad: function( anchorLink, index ) {
if( index == 1 ) {
console.log( 'afterload function' );
$( '#video' ).get( 0 ).play();
}
}
} );
$( '#section0 video' ).on( 'loadedmetadata', function() {
console.log( 'onloadedmetadata function' );
var $width, $height, // Width and height of screen
$vidwidth = this.videoWidth, // Width of video (actual width)
$vidheight = this.videoHeight, // Height of video (actual height)
$aspectRatio = $vidwidth / $vidheight; // The ratio the video's height and width are in
( adjSize = function() { // Create function called adjSize
$width = $( window ).width(); // Width of the screen
$height = $( window ).height(); // Height of the screen
$boxRatio = $width / $height; // The ratio the screen is in
$adjRatio = $aspectRatio / $boxRatio; // The ratio of the video divided by the screen size
// Set the container to be the width and height of the screen
$( '#section0' ).css( { 'width' : $width+'px', 'height' : $height+'px' } );
if( $boxRatio < $aspectRatio ) { // If the screen ratio is less than the aspect ratio..
// Set the width of the video to the screen size multiplied by $adjRatio
$vid = $( '#section0 video' ).css( { 'width' : $width*$adjRatio+'px' } );
} else {
// Else just set the video to the width of the screen/container
$vid = $( '#section0 video' ).css( { 'width' : $width+'px' } );
}
} )(); // Run function immediately
// Run function also on window resize.
$( window ).resize( adjSize );
} );
function iedetect( v ) {
var r = RegExp( 'msie' + ( !isNaN(v) ? ( '\\s' + v ) : '' ), 'i' );
return r.test( navigator.userAgent );
}
}
$( document ).ready( function(){
addFullPage();
console.log( 'document ready function' );
mobMenu();
} );
function addBlacklistClass() {
$( 'a' ).each( function() {
if ( this.href.indexOf( '/wp-admin/' ) !== -1 || this.href.indexOf( '/wp-login.php' ) !== -1 ) {
$( this ).addClass( 'wp-link' );
}
} );
}
$( function() {
addBlacklistClass();
var settings = {
anchors: 'a',
blacklist: '.wp-link',
onStart: {
duration: 1000,
render: function ( $container ) {
$( '#content' ).addClass( 'fade-out' );
}
},
onAfter: function( $container ) {
addFullPage();
console.log( 'on after function in smoothstate' );
mobMenu();
$( '#content' ).removeClass( 'fade-out' );
var $hash = $( window.location.hash );
if ( $hash.length !== 0 ) {
var offsetTop = $hash.offset().top;
$( 'body, html' ).animate( {
scrollTop: ( offsetTop - 60 ),
}, {
duration: 280
} );
}
}
};
$( '#page' ).smoothState( settings );
} );
} )( jQuery );
Ultimately the cleanest solution for me was to simply use CSS to resize the video rather than JQuery. I'm also relying on the built-in functionality of Fullpage.js to play/pause the video as it goes in and out of the viewport rather than trying to manipulate it myself.
The DOM play() exception is still thrown but after much testing it doesn't seem as though it's causing any harm on the front-end.
#fullpage .section video { position:absolute; top:0; left:0; width:100%; height:100%; display:none; }
#media ( min-aspect-ratio:16/9 ) {
#fullpage .section video { width:100%; height:auto; }
}
#media ( max-aspect-ratio:16/9 ) {
#fullpage .section video { width:auto; height:100%; }
}
I am working with this jquery.mobile example to use swipe to navigate pages.
jquery.mobile swipe-page example
Now I don´t want to have the swipe on the whole page. I want to bind it only to an div element.
I have a div element on my page
<div id="divSWIPE"></div>
I have looked at the source code of the example and I think I found the part that handles the swipe event.
// The same for the navigating to the previous page
$( document ).on( "swiperight", ".ui-page", function( event ) {
var prev = $( this ).jqmData( "prev" );
if ( prev && ( event.target === $( this )[ 0 ] ) ) {
navprev( prev );
}
});
I have tried to modify this but I can´t get this working only on the div element.
I have tried this
$( "#divSWIPE" ).on( "swiperight", ".ui-page", function( event ) {
and this
$( document ).on( "swiperight", "divSWIPE", function( event ) {
But this doesn´t work.
How can I bind this to my div element?
Attack swipe listeners on pagecreate. The below code will check if there is a page in DOM before the current page. Or retrieve value from custom attribute in page div data-prev.
$(document).on("pagecreate", function (e) {
var page = e.target;
$("#divSwipe", page).on("swiperight", function () {
var prev = $(this).closest(".ui-page").prev("[data-role=page]");
/* or read custom attribute */
var prev = $(this).closest(".ui-page").data("prev");
if ( prev.length > 0 || typeof prev != "undefined" ) {
/* navigate or do something else */
$.mobile.pageContainer.pagecontainer("change", prev);
}
});
});
I have a web application built on JQuery Mobile.
I've been looking for a way to have certain divs (which have data-role="collapsible") be collapsed when viewed on a mobile device, but expanded if viewed on a desktop browser.
I know there are a lot of similar questions, but I haven't been able to get any of those solutions to work. Here's what I've tried.
The divs have a class of mobileHide
<script type="text/javascript">
/*collapse non-crucial sections when viewed on mobile device*/
/* this works while resizing desktop browser, but can't resize mobile browser*/
$(window).on('resize', function(){
var w = $(window).width();
if(w >= 540 ) {
$( ".mobileHide" ).trigger( "expand" );
}else{
$( ".mobileHide" ).trigger( "collapse" );
}
});
/* Tried setting #media to make .hide-element {display:none} if screen size less than 540px (which worked in hiding that element) then set is_mobile to true. Also tried doing the same without the is_mobile and just using "if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) )"*/
$(window).resize(function() {
var is_mobile = false;
if( $('.hide-element').css('display')=='none' {
is_mobile = true;
}
if(!is_mobile) {
$( ".mobileHide" ).trigger( "expand" );
}else{
$( ".mobileHide" ).trigger( "collapse" );
}
});
/*Also tried this without being in a window.resize function. The alert works when viewed on mobile device, but the collapse and expand don't*/
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
/*alert("I am mobile!");*/
$( ".mobileHide" ).trigger( "collapse" );
} else {
$( ".mobileHide" ).trigger( "expand" );
}
</script>
I didn't have all of those running at once, but each piece that I commented on was the only part that was active at the time.
Any insight into why the last one detects mobile device and displays the alert (when it's not commented out) but won't trigger the collapse when it detects mobile device would be much appreciated!
Here is a working DEMO
The function CollapsiblesOnSize() checks the window width and then either collapses or expands all elements with class of mobileHide. You can then call this on window resize, orientation change and jQM's pageshow:
$(document).on("pageinit", "#page1", function () {
CollapsiblesOnSize();
$(window).on("resize orientationchange", function(){
CollapsiblesOnSize();
});
});
function CollapsiblesOnSize(){
var w = $(window).width();
if(w >= 540 ) {
$( ".mobileHide" ).trigger( "expand" );
}else{
$( ".mobileHide" ).trigger( "collapse" );
}
}