I'm trying to create an element in a Wordpress site where a piece of content begins partway down the screen, and sticks to the top of the screen when the user scrolls down.
I've tried various things, and none of them have worked. The most recent attempt uses Javascript to give and take away a class to the content I'm trying to move/fix.
The code is
jQuery( document ).ready(function($) {
alert( "test1!" );
var wrap = $("#wrap");
wrap.on("scroll", function(e) {
if (this.scrollTop > 147) {
wrap.addClass("fix-search");
alert("test2");
} else {
wrap.removeClass("fix-search");
}
});
});
The file is enqueuing properly since the first test alert ("test1" fires, but "test2" doesn't fire as I scroll down the screen. I've had that same piece of code working in a modified version of the original code on codepen (http://codepen.io/anon/pen/NqKKVN) so I can only assume this is something weird with Wordpress interacting with Javascript.
So yeah, anyone know a way to either do that I'm wanting to do in a way that will work with wordpress, or to get the above piece of code working properly?
EDIT: This has been solved. For the reference of anyone else with the same problem the piece of code that eventually worked was
jQuery( document ).ready(function($) {
var scrollTop = $(window).scrollTop();
function scrollUpdate() {
var scrollTop = $(window).scrollTop();
var wrap = $("#menu-all-pages");
if (scrollTop > 147) {
wrap.addClass("fix-search");
console.log("Menu at top");
} else {
wrap.removeClass("fix-search");
console.log("Menu at set point");
}
console.log(scrollTop);
}
window.onscroll = scrollUpdate;
});
I have implemented a similar solution in my blog a few years ago. I got it working by scripting this way:
Add a variable scrollTop which would contain the value in pixels
scrolled from the window top.
var scrollTop = $(window).scrollTop();
See, I use jquery function scrollTop applied to the selected object "window". It would return the value scrolled from the very top of the browser. It does work on Wordpress, I have tried it on my blog.
Put this code in a function scrollUpdate. We'll call it later to update
the scroll value from top
function scrollUpdate() {
var scrollTop = $(window).scrollTop();
}
The function should also contain all the logic checking the scrollTop value and thus applying styles and etc.
Let's make this function be called on every scroll.
window.onscroll = scrollUpdate;
Try it yourself!
P.S. I got a weird feeling, but you should better use hide / show instead of adding a whole css class to the page.
Related
I have created a script that adds the scrollTop value to the height of a DIV
var scroll = $(this).scrollTop();
console.log(scroll);
function scrollH() {
document.getElementById("overlay").style.height = scroll + 'px';
}
document.getElementById("overlay").addEventListener("scroll", scrollH());
I need this style to keep updating (I'm making a progress bar). Currently it only changes when I refresh the page.
Thanks in advance
(Sorry if I did not follow the correct question format for this site, this is my first question :L )
You want to apply styles via JavaScript after the DOM has loaded.
JQuery helps with this:
$(document).ready(function() {
//do something to css
});
https://learn.jquery.com/using-jquery-core/document-ready/
You could apply a listener to whatever event is triggering an update, and then replace or fill the progressbar with it's new value.
I am new to web programming and I stumbled on something strange while working on my website. I use Wordpress but here I had to dive in the Javascript code to get it done.
What I want to achieve is the following:
I want people to get to see the header of my website when they arrive but not be bothered by it once they read stuff on my site.
What I figured out is that I want the website to scroll down if a) people are at the top of the site and b) if they click on a menu link. When people are already on the site and click on a menu item to change pages, I would like to maintain the scroll position of where they were before.
I tried two versions:
This one works like a charm except that the function executes on each reload of the site
var scroll_position = localStorage.getItem('scroll_position');
var header_height = document.getElementById('masthead').offsetHeight;
var menubar_height = document.getElementById('top-bar').offsetHeight;
var page_height = header_height - menubar_height;
jQuery(function () {
if (window.pageYOffset == scroll_position){
jQuery(window).scrollTop(page_height);
}
else{
jQuery(window).scrollTop(scroll_position);
}
});
But as I wanted to execute the function only on clicking one of the menu items, I tried:
jQuery("#top-menu ul li a").click(function(){
if (window.pageYOffset == scroll_position){
jQuery(window).scrollTop(page_height);
}
else{
jQuery(window).scrollTop(scroll_position);
}
});
and suddenly the scroll_position variable doesn't change value as before...
I spend the whole day trying to figure this out and I would appreciate very much if someone out there could tell me what I'm doing wrong!
Thanks in advance.
According to the code you gave us, try this
jQuery(function () {
var header_height = document.getElementById('masthead').offsetHeight;
var menubar_height = document.getElementById('top-bar').offsetHeight;
var page_height = header_height - menubar_height;
jQuery("#top-menu ul li a").click(function(e){
e.preventDefault();
var scroll_position = localStorage.getItem('scroll_position');
if (window.pageYOffset == scroll_position){
jQuery(window).scrollTop(page_height);
}
else{
jQuery(window).scrollTop(scroll_position);
}
});
});
I'm assumig that header_height, menubar_height and page_height can't get altered once the page is loaded, thats why we init them on the page load, not on the click.
Hope it's gonna help you
I have created the following application using iScroll: http://preview.na-software.co.uk/Demo/FutureLearning4/#/section-0
As the user flicks left and right or clicks the arrows in the bottom corners, the application moves the content sections it updates the history by changing the hash so that the user can move back and forth to other sections and bookmark them etc.
However! If you access a hash like: http://preview.na-software.co.uk/Demo/FutureLearning4/#/section-2 and then navigate a few sections and then use the back buttons two issues happen:
1.) It scrolls to the first screen (even though currentSection is correct, and iScroll has been told the correct section).
2.) If you click the back or forward button multiple times, you stop the animation and cause it to become confused and stick in between two sections.
Looking into the code, and seeing that the correct indexes and elements are being passed to iScroll on hashchange, and console logging out the offsets, I've discovered the issue is cause because the offsets are incorrectly set... however just doing refresh() won't fix the issue, as it will then reset the position.
Can anyone see where the problem is or see a way to fix this?
I should note that this bug ONLY happens if you come into the application on a URL that isn't section 0 and then scroll around the application. This is because the offsets will be created correctly by your interactions. But if you come into a URL like section 3, then the offsets will be incorrect and so the hashchanges don't work correctly, if that makes sense.
The hashchange method looks like:
// handle hashchange events
$(window).hashchange( function(){
// read the hash to find out what the new section number is
var nums = location.href.match(/(section)-\d+/g).map(
function(x){ return +x.replace(/\D/g,"") }
);
// set currentSection
currentSection = nums[0];
// if the hashchange was called by user scrolling
if(hashCalledByScroll){
// no need to anything as they have already updated hash and scrolled
hashCalledByScroll = false;
} else {
// find the section to scrollTo
sectionToScrollTo = $('#horizontal > .sections > .section').eq(currentSection).attr('id');
// tell iscroll to scroll to the section
horizontal.scrollToElement( '#' + sectionToScrollTo, null, null, true );
}
// hide the menu on hashchange
hideMenu();
});
Testing your site, I noticed the following: Whenever I access the site via section-3 and then enter the url for section-2, the navigation would instead send me to section-0.
I believe this is the same behaviour as you are experiencing in 1).
So I investigated and came to the following analysis:
In the function horizontal.scrollToElement( '#' + sectionToScrollTo, null, null, true )
iScroll retrieves the utils.offset(el) [iScroll.js#772] for the given el-ement. This offset tells it, where the element to scroll to is.
iScroll goes through the element and all of its offsetParents to add up their offsets. This is where things are breaking: <div class="sections"> has a negative offset to its parent, which imho it should not have.
This, in turn, messes up the scrollTo-coordinates.
To see what I am talking about: document.querySelector('.sections').offsetLeft
This has all just been analysis. My approach to fix this would be to avoid scrollToElement() and instead use scrollTo():
...
} else {
// find the section to scrollTo
sectionToScrollTo = $('#horizontal > .sections > .section').eq(currentSection).attr('id');
// tell iscroll to scroll to the section
var posLeft = -$('#' + sectionToScrollTo)[0].offsetLeft;
var posTop = -$('#' + sectionToScrollTo)[0].offsetTop;
horizontal.scrollTo(posLeft, posTop, 1000);
}
// hide the menu on hashchange
hideMenu();
});
Thus, just calculate the location of the section you want to go to yourself.
About 2) I am not sure if there is much one can do about it. Jumping around quickly breaks a lot of carousels. Maybe a delayed callback to scrollEnd, verifying the validity of the current state.
Another thing I noticed is that you can accidentally stop the transition. Try to click, hold and release the cursor midway a transition - you need to be quick.
Hope this helps.
Found not best solution and it doesn't solve main problem, but it works.
$(window).hashchange(function () {
if (hashCalledByScroll) {
hashCalledByScroll = false;
} else {
var hpage = window.location.hash;
var hpage = hpage.replace('#/section-', ''); //get number of target page
var cpage = currentSection; //number of current page
var count = parseInt(hpage) - parseInt(cpage); //difference
while (count > 0) { //if difference positive: go forward count-times
horizontal.next();
count--;
}
while (count < 0) { //if difference negative: go backward count-times
horizontal.prev();
count++;
}
}
hideMenu();
});
FIDDLE
I'm trying to make a single down arrow that jumps to the next ID on the page as you scroll down. I don't really know JavaScript so I'm trying to keep it as simple as possible. I thought, as there are only a few sections, that I could just hide and display different divs with arrows that have different targets. I used two different codes to arrive at this, but doesn't seem to be working. Any ideas?
<script type="text/javascript">
$(window).scroll(function(){
if($(window).scrollTop() >= 800) {
var elem = document.getElementById("arrow");
elem.setAttribute("style","display:none;");
} else {
elem.setAttribute("style","display:inline;");
}
});
</script>
I'm not sure I understand exactly what you want to do, but your code can be simplified a bit by taking advantage of the shortcuts that jQuery provides.
//When the document is ready...
$(function(){
//Select the arrow just once
var arrow = $("#arrow");
//Attach a scroll event to the window
$(window).scroll(function(){
//See what the scroll position is
var scrollPos = document.body.scrollTop;
//When the document has scrolled to a certain point or more, hide the arrow.
//Otherwise, show it.
if(scrollPos >= 800){
arrow.hide();
} else {
arrow.show();
}
});
});
Here's a brief demo of it in action: http://jsfiddle.net/Bt35Q/
UPDATE:
I was able to get my scroller working as desired but I feel like I have hacked around the actual issue and would love it if anyone has a more solid answer, I've updated and noted in the snippets below the new jQuery I'm using.
I'm using iScroll-4 (http://cubiq.org/iscroll-4) for an iPad/Android web app, everything's working perfectly with the swipes and scrolling but I have a table of contents at the beginning of the app that allows users to jump to specific areas of the scroller --
I'm using the iScroll function scrollToElement(element, duration) in order to jump to the different areas. Also using scrollToPage(page, duration) to allow the user to manually navigate forward and backward one page at a time.
While watching the console logs the currPageX variable updates when I navigate with the scrollToPage function and when I swipe, but when using the scrollToElement the currPageX variable does not update.
Therefore if I jump to an element and then navigate forward with scrollToPage('next', 0) it will go backwards and navigate me to the next page after the table of contents.
I have tried using the scroll.refresh() function after scrollToElement, before, putting the function inside a timeout, etc. and I can't figure out why the currPageX is not updating.
Here's a snippet of the jQuery code that I'm using the two different functions:
// TO NAVIGATE FORWARD AND BACKWARDS
$('span.control').on('click', function() {
var slideDir = $(this).attr('data-dir');
if (slideDir == 'prev') {
var tehPg = tehScroll.currPageX-1;
} else if (slideDir == 'next') {
var tehPg = tehScroll.currPageX+1;
}
tehScroll.scrollToPage(tehPg, 0);
return false;
});
// TO JUMP FROM CONTENTS
$('li[data-page="toc"] span').on('click', function() {
var toPage = $(this).attr('data-page');
tehScroll.scrollToElement('li[data-page="'+toPage+'"]', 800);
// ADDED THE FOLLOWING LINE TO MANUALLY SET currPageX after scrolling!
tehScroll.currPageX = $('#slides li[data-page="'+toPage+'"]').index();
return false;
});
Did you consider using jquery-mobile-iscrollview widget plug-in? - there is a function scrollToPage(pageX, pageY, time), works well for me...
best
M