I've written a script that increases the nav menu top-margin when my website is loaded as a web app on an iPad, however I'd like to add a third condition: after the user scrolls down.
My current script:
<script type='text/javascript'>
jQuery("div").ready(function(){
if (("standalone" in window.navigator) && window.navigator.standalone) {
var array = window.navigator.userAgent.match("iPad"); if(array!=null && array.length == 1)
jQuery(".menu-secondary-wrap").css("marginTop", "20px");
};
});
</script>
I'd like to add:
jQuery(document).scroll(function(){
if(jQuery(this).scrollTop() > 175){
I'm just not sure how to do this - I can't seem to get the syntax right.
Any help would be really appreciated!
Add this script before the closing head tag
window.onscroll = function (e) {
var scrollTopVal = window.pageYOffset || document.body.scrollTop;
if(parseInt(scrollTopVal,10) > 175){
//Your Stuff Here
}
}
No need for jQuery. DEMO
Related
I am trying to get a drawing animation effect similar to https://stackoverflow.com/a/45378478 (Preview: https://codepen.io/jbanegas/pen/LjpXom) to load when the user scrolls to this section of the page. It's intended to add multiple of these drawing boxes as the user navigates the page.
I realize that jQuery is sort of outdated now, but this is on a WordPress website that already utilizes this framework.
jQuery
<script type='text/javascript'>
$(document).ready(function(){
$('.thisisatest').addClass('draw');
});
</script>
HTML
<div class="thisisatest"></div>
I've tried replacing the .ready() with:
onload - https://www.w3schools.com/jsref/event_onload.asp
.scroll() - https://api.jquery.com/scroll/
Any help would be greatly appreciated.
You are missing the basics. Apart from adding on scroll event you need to find out if element is in view port obviously.
Here is vanilla JS solution...
It will work on all div's with content and .thisisatest class.
References Read the link on how the isInViewport function work.
var isInViewport = function(elem) {
var distance = elem.getBoundingClientRect();
return (
distance.top >= 0 &&
distance.left >= 0 &&
distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
distance.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
// read the link on how above code works
var findMe = document.querySelectorAll('.thisisatest');
window.addEventListener('scroll', function(event) {
// add event on scroll
findMe.forEach(element => {
//for each .thisisatest
if (isInViewport(element)) {
//if in Viewport
element.classList.add("draw");
}
});
}, false);
EXAMPLE: jsfiddle
I am trying to mess around with some JS and using snippets trying to get them to work on clean WP installs so that I understand how to add them Wordpress properly.
I am working with JSFiddle
This is the link that im testing it on
(function() {
var delay = false;
$(document).on('mousewheel DOMMouseScroll', function(event) {
event.preventDefault();
if(delay) return;
delay = true;
setTimeout(function(){delay = false},200)
var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;
var a= document.getElementsByTagName('a');
if(wd < 0) {
for(var i = 0 ; i < a.length ; i++) {
var t = a[i].getClientRects()[0].top;
if(t >= 40) break;
}
}
else {
for(var i = a.length-1 ; i >= 0 ; i--) {
var t = a[i].getClientRects()[0].top;
if(t < -20) break;
}
}
$('html,body').animate({
scrollTop: a[i].offsetTop
});
});
})();
Here is the fiddle I am trying to implement.
It seems to be trying to do something on scroll and gets stuck.
Steps I have taken:
Added HTML to page
Added CSS to style.css
Added link to Jquery in header
Added the JS snippet in a tag before
I'm thinking maybe it has something to do with the fact that its got more elements on the page than just a and tag maybe? Seems to be getting caught on the header. This JS is just kind of hard for me to reverse engineer with the little that I know unfortunately.
Thanks.
The javascript listens to your mouse wheel event. If you mouse wheel up or down, it will first check if you're currently "wheeling" too fast. If you are, it will delay you. If you're not, then it will scroll (animate) to your next anchor tag and that anchor tag will be up top.
EDIT: I see you're getting a js error on your site. Remove the $ from the
$(function() {
var delay = false;
//blah blah
}
I have a twitter feed I currently display on my website when the viewport is 1250px or wider. So when the screen is wide enough, it calls in some content (which calls the javaScript file for the twitter feed.
My current code is this...
function checkSize(){
if ($(window).width() > 1250) {
$(".tweet").load("/ajax/");
}
}
checkSize();
$(window).resize(function() {
checkSize();
});
Now this works fine, however as the twitter script is near the bottom of the page, how can I only load the script when the div appears in user view?
I have tried something like this however it does not work
function checkSize(){
if ($(window).width() > 1250 && $(".tweet").is(':visible')) {
$(".tweet").load("/ajax/");
}
}
So to confirm, I want to only call in this content when the screen width is 1250px or wider AND when the user is at the bottom of the page so the parent div is visible (.tweet).
Any help would be appreciated.
I have added a codepen to test with here http://codepen.io/anon/pen/ezksD
This will determine if the user has scrolled down far enough for it to be visible.
function checkSize(){
if ($(window).width() > 1250 && $(".tweet").offset().top < $(window).scrollTop()) {
$(".tweet").load("/ajax/");
}
}
I think you'll have to find out how far the user has scrolled to be able to identity if the div is visible.
So what you could do is (wrote this from mobile and didn't check your code for syntax errors):
var loaded = false;
var proximity = 0;
if (loaded == false){
$(window).scroll(function () {
var scrollBottom = $(".tweet").offset().top - $(window).scrollTop();
var windowWidth = $(window).width();
if (scrollBottom <= proximity && windowWidth > 1250 && loaded == false)
{
$(".tweet").load("/ajax/");
loaded = true;
}
});
}
Hope that helps you.
I have a strange issue that might have to do with jQuery document ready. Below is an html and script block that contains the usual social networking scripts. The Javascript block below displays the dd_outer div on the left edge of the body div, and when the browser window is shrunk, the div is faded out and the dd_footer div is faded in. The fadein and fadeout between the two divs works OK.
The problem is two fold: one issue is when the browser window is full width (1200px+), the Facebook script will not load and display consistently; it sometimes appears and sometimes doesn't, sometimes after a page reload and sometimes doesn't. (No browser or .htaccess caching is involved). Only the Facebook share fails to show consistently; all other services show OK.
The second problem that when the browser window is narrow - 650 px or so, when the dd_outer div is not displayed and the dd_footer div is - the footer div will not show on a page reload until the browser window is moved the smallest amount. Then the the div will display, Facebook share and all. For a mobile device, this is a problem because the browser window will be narrow to begin with and shouldn't need to be "nudged" to make the dd_footer div display.
This problem may have come into play because I have adapted this code from a WordPress plugin that used options to set the position of the dd_outer div and scroll height. That's the reason for the variables above the document ready call.
Is this the issue with what seems to be a document ready issue?
How can the variables be integrated into the script itself? It doesn't matter if they are hardcoded; I can change them when needed.
I'd throw this in a jsfiddle to demo but the divs won't realistically float with the window resizing.
I haven't included the CSS for clarity.
This is the html and social script block:
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'>
<div class="sbutton"><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like layout="box_count" show_faces="false" font=""></fb:like></div>
<div class="sbutton">
Tweet<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div>
<div class="sbutton"><script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script><g:plusone size="tall"></g:plusone></div>
<div class="sbutton"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/Share" data-counter="top"></script></div>
</div></div></div>
In the footer is <div id="dd_footer">that contains the same social scripts as above</div> and are faded in and out by the script below:
This is the jQuery that positions the dd_outer social services to the left and fades it out and fades in the dd_footer div.
<script type="text/javascript">
var dd_top = 0;
var dd_left = 0;
var dd_offset_from_content = 70; var dd_top_offset_from_content = 10;
jQuery(document).ready(function(){
var $floating_bar = jQuery('#dd_ajax_float');
var $dd_start = jQuery('#dd_start');
var $dd_end = jQuery('#dd_end');
var $dd_outer = jQuery('.dd_outer');
// first, move the floating bar out of the content to avoid position: relative issues
$dd_outer.appendTo('body');
dd_top = parseInt($dd_start.offset().top) + dd_top_offset_from_content;
if($dd_end.length){
dd_end = parseInt($dd_end.offset().top);
}
dd_left = -(dd_offset_from_content + 55);
dd_adjust_inner_width();
dd_position_floating_bar(dd_top, dd_left);
$floating_bar.fadeIn('slow');
if($floating_bar.length > 0){
var pullX = $floating_bar.css('margin-left');
jQuery(window).scroll(function () {
var scroll_from_top = jQuery(window).scrollTop() + 30;
var is_fixed = $dd_outer.css('position') == 'fixed';
if($dd_end.length){
var dd_ajax_float_bottom = dd_end - ($floating_bar.height() + 30);
}
if($floating_bar.length > 0)
{
if(scroll_from_top > dd_ajax_float_bottom && $dd_end.length){
dd_position_floating_bar(dd_ajax_float_bottom, dd_left);
$dd_outer.css('position', 'absolute');
}
else if ( scroll_from_top > dd_top && !is_fixed )
{
dd_position_floating_bar(30, dd_left);
$dd_outer.css('position', 'fixed');
}
else if ( scroll_from_top < dd_top && is_fixed )
{
dd_position_floating_bar(dd_top, dd_left);
$dd_outer.css('position', 'absolute');
}
}
});
}
});
jQuery(window).resize(function() {
dd_adjust_inner_width();
});
var dd_is_hidden = false;
var dd_resize_timer;
function dd_adjust_inner_width() {
var $dd_inner = jQuery('.dd_inner');
var $dd_floating_bar = jQuery('#dd_ajax_float')
var width = parseInt(jQuery(window).width() - (jQuery('#dd_start').offset().left * 2));
$dd_inner.width(width);
var dd_should_be_hidden = (((jQuery(window).width() - width)/2) < -dd_left);
var dd_is_hidden = $dd_floating_bar.is(':hidden');
if(dd_should_be_hidden && !dd_is_hidden)
{
clearTimeout(dd_resize_timer);
dd_resize_timer = setTimeout(function(){ jQuery('#dd_ajax_float').fadeOut(); }, -dd_left);
jQuery('#dd_footer').fadeIn();
}
else if(!dd_should_be_hidden && dd_is_hidden)
{
clearTimeout(dd_resize_timer);
dd_resize_timer = setTimeout(function(){ jQuery('#dd_ajax_float').fadeIn(); }, -dd_left);
jQuery('#dd_footer').fadeOut();
}
}
function dd_position_floating_bar(top, left, position) {
var $floating_bar = jQuery('#dd_ajax_float');
if(top == undefined) top = 0 + dd_top_offset_from_content;;
if(left == undefined) left = 0;
if(position == undefined) position = 'absolute';
$floating_bar.css({
position: position,
top: top + 'px',
left: left + 'px'
});
}
</script>
jQuery .ready() does not wait for iframes and other external media to load. These social buttons tend to work by inserting an iframe. The load event does wait for iframes etc, so you could try using that event instead, i.e.
jQuery(window).load(function () {
/* put the code you had inside .ready() here */
});
The problem comes with your idea: $(document).ready() fires when the DOM is ready, not when all scripts are ready!
an idea would be to search for trigger of that social-APIs you are using or just delay your calculations (e.g. via setTimeout).
Keep in mind that they are asyncron, even if you specify "async" on the script-tag to be false, you still dont know when they will activate or are finished.
I suggest to use the standard DOM event window.onload if you want to make sure that all the external assets, scripts, images, etc. are loaded first before you do something:
window.onload = function () {
// your script that needs to run after all the external assets are loaded
}
Reference: https://developer.mozilla.org/en-US/docs/DOM/window.onload
I just ran into similar problems with the facebook script... I just used the integration in the HEAD-section with javascript and added an "asynchronous"-attribute to the javascript-embedding script which then fires an asynchronous "heeey, facebook is ready now, too"-event to my jQuery-eventqueue...
I can't help you in detail, because I don't totally understand what you WANT to do and would reorganize the whole code A LOT... so - contact me private (email/skype) or try figuring out... I used that lines of code: pastie.org/private/9m4b9eet1dzzkl6duqpkrg
I am currently using a smooth scroll script from css tricks.
The problem I'm having is that I have used 's as links with onclick links to anchor elements.
You can see it here. The problem is the script doesn't look for what I need it to, the links at the top (the divs) do not get found by the script so do not smoothly scroll to the anchor. Whereas the about, services, contact links (the text ones inside the green thingys) scroll smoothly.
I am complete jquery and javascript noob and do not know how to alter the script to include the onclick divs or to make a script to make it scroll smoothly to the anchors.
I need the script to scroll smoothly from both the div links and text links or I need a duplicate script that works with the div links (2 scripts that do text links and div links - The one I'm using atm only does text)
<script>
$(document).ready(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
$('a[href*=#]').each(function() {
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
var $target = $(this.hash), target = this.hash;
if (target) {
var targetOffset = $target.offset().top;
$(this).click(function(event) {
event.preventDefault();
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
location.hash = target;
});
});
}
}
});
// use the first element that is "scrollable"
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
</script>
I don't know if you use a javascript framework like jQuery. For websites like this I always use the jQuery plugin 'Localscroll'. It always works fine cross-browser.
You can see the documentation for the plugin here:
http://flesler.blogspot.com/2007/10/jquerylocalscroll-10.html
It's very easy to use.
Good luck!
You can use anchors instead of divs in the nav, right now you're doing
<div id="whatever" onclick="window.location=#portfolio">portfolio</div>
but that's not semantic, and it doesn't work the way you want it to, so that's doubleplus not good. use
<a id="whatever" href="#portfolio" style="display:block">portfolio</a>
then the code from css tricks should work... if it's clickable it should probably be a button or an anchor.
the anchor tags in your body work as expected, btw...