So here is the fiddle link https://jsfiddle.net/malakar369/y5Lppeg0/8/
jQuery(document).ready(function ($) {
$('.custom-click').on('click', function (e) {
e.preventDefault();
var href = $(this).attr('href');
var current_div = $(href);
var animateTo = $(href).position().top ;
console.log(animateTo);
$('#main-height-container').animate({scrollTop: animateTo},"slow");
});
});
It works if my div is at the top of the page. However, since it is not at the top i am having and extensive amount of issue. Could any of you guys could have a look at it and help me out.
Thanks
$(href).position().top is in window coordinates
Try this
var animateTo = $("#main-height-container").scrollTop() - $("#main-height-container").position().top + $(href).position().top;
https://jsfiddle.net/y5Lppeg0/9/
Related
This seems like an easy fix, but can't seem to figure it out. I have a table that spawns a fixed header whenever you scroll on it. It's working well, however, an unconnected link near the top of this page, via jquery, scrolls the cursor to the bottom of the page til it hits an anchor. As a result, it quickly moves over the table, spawning the fixed menu, then after reaching the anchor, the fixed menu awkwardly sits there for a second or two, then disappears.
I'm trying to prevent that by disabling the function on click of the link. I've tried e.preventDefault (), but no joy. Here's the fiddle and code (so looking to prevent the fixed "Header / Description" row when you click the link).
Fiddle
// top edge of table
var element_menu_hdr = $(".row-1").offset().top;
var element_menu_end_check = $(".row-12").offset().top;
$(window).on("scroll", function fixmenu() {
var y_scroll_pos = window.pageYOffset;
var scroll_menu_hdr = element_menu_hdr;
var scroll_menu_end_check = element_menu_end_check;
if(y_scroll_pos >= scroll_menu_hdr) {
if($('.affix').length === 0){
$('.row-1.odd').wrap('<table class="tablemain affix view"></table>');
}
} else if (y_scroll_pos < scroll_menu_hdr) {
$('.tablemain.affix.view').contents().unwrap();
} else {
}
});
// bottom edge of table
var element_menu_end = $(".row-12").offset().top;
$(window).on("scroll", function fixmenubtm() {
var y_scroll_pos2 = window.pageYOffset;
var scroll_menu_end = element_menu_end;
if(y_scroll_pos2 > scroll_menu_end) {
$('.tablemain.affix.view tbody').contents().unwrap();
} else {
}
var myVar = y_scroll_pos2;
console.log(myVar, "y_scroll_pos2");
var myVar2 = element_menu_end;
console.log(myVar2, "element_menu_end");
});
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});
});
I'm developing a wordpress theme that has a function of changing background image by hovering menu item(each menu item is attached different image). On mobile, I'd like to change background image just by scrolling so that viewers don't need to click each menu to change the background image.
This is the method I implemented to change background by hovering.
http://codepen.io/nummelin/pen/kzaso
// When any of the a's inside of sidebarContainer are hovered
$( ".sidebarContainer a" ).hover(function() {
// Removes all previous classes but keeps sidebar1
$('.sidebar1').removeClass().addClass('sidebar1');
// Splits up the URL on the current href
var URI = $(this).attr('href').split('/');
console.log(URI[2]);
// Applies the last part of the URL to sidebar1
$('.sidebar1').addClass(URI[2]);
});
Achieving with scrolling, I think I need a function that hovering menu item by its position like the image below.
Does anyone have any ideas how to achieve this? I've been exploring a plugin or sample code similar to this, but haven't found any...
Any advices would be appreciated.
Okay, so this is the code I wrote. Hope it helps. I've worked on cross-fading effect but it wasn't that easy. If someone tried please teach me how to do it.
Demo on Codepen:
http://codepen.io/bavavava/pen/rrNpaY
jQuery(function($){
'use strict';
$(document).ready(function(){
var elem = $('li.list-item'),
$listPosition = $.map(elem, function(el, i) { return $(el).offset().top; }),
$listURL = $.map(elem, function(el,i) { return $(el).find('a').attr('href'); }),
$bg = $('.container');
console.log($listPosition);
console.log($listURL);
//PRELOAD IMAGES
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
$($listURL).preload();
//SCROLL CHANGE
$(window).on('scroll', function () {
var windowScroll = $(this).scrollTop();
$.each($listPosition, function (i, pos) {
if (windowScroll >= pos) {
$bg.css('background', 'url(' + $listURL[i] + '), black no-repeat center center fixed');
}
});
});
});
});
In an ideal world i didn't want to use a table for this but it proved ideal for the layout for such an intense data table. Anyhow, when the user clicks on the a header of a section i want the windwo to remain at the top of that section and not at the bottom of the section that is now opened. The javascript i have in there currently is:
$(document).ready(function () {
$('tr.parent').next('tr.child').hide();
$('a.toggle').on('click', function (e) {
e.preventDefault();
var $this = $(this),
$child = $this.closest('tr.parent').next('tr.child');
$this.closest('tr.parent').siblings('tr.child').not($child).hide();
$child.toggle();
})
});
I've created a Fiddle Here so you can see the html table opening/closing with the javascript, but just need help on how to keep the content to scroll to the top of that header/section when clicked on and opened.
http://jsfiddle.net/aaronblomberg/jtu49v22/
thanks in advance! a fiddle example back would be ideal!
Here's an animated scroll that would get you started:
$('a.toggle').on('click', function (e) {
e.preventDefault();
var $this = $(this),
$child = $this.closest('tr.parent').next('tr.child');
$this.closest('tr.parent').siblings('tr.child').not($child).hide();
$child.toggle();
// scroll heading to page top with arbitrary 60px difference
var top = $this.offset().top -60;
$('html,body').animate({scrollTop: top})
});
DEMO
I have a long list of items and when I clicked into each item and return to the main list, the scroll position was lost.
How can I return to the same exact scroll position using jQuery? Is there any easy way to do it?
$(document).ready(function() {
$('.update-button').click(function (){
sessionStorage.scrollPos = $(window).scrollTop();
console.log(sessionStorage.scrollPos);
});
});
var init = function () {
//get scroll position in session storage
$(window).scrollTop(sessionStorage.scrollPos || 0)
};
window.onload = init;
Above is what my code looks like. I tried to log the position and sessionStorage.scrollPos was 0. I am pretty sure I scrolled the page to somewhere.
Help is greatly appreciated.
You need to store value of scroll position in sessionStorage (or any storage) and re use it again on page load.
$(window).scroll(function () {
//set scroll position in session storage
sessionStorage.scrollPos = $(window).scrollTop();
});
var init = function () {
//get scroll position in session storage
$(window).scrollTop(sessionStorage.scrollPos || 0)
};
window.onload = init;
Just modifying #Rayon Answer if it doesn't work someone.
$("body").on("scroll", function () {
//set scroll position in session storage
sessionStorage.scrollPos = $(window).scrollTop();
});
var init = function () {
//get scroll position in session storage
$("body").scrollTop(sessionStorage.scrollPos || 0)
};
window.onload = init;
You can replace the $("body") with the top most element in your HTML. I am using framework7 mobile applicaiton and I need to use $(".page-content"). It worked for me.
No easy solution, but on the click event where the redirect takes place, get the current scroll position using
var scroll = $(window).scrollTop();
Then store the value of the scroll variable into the localstorage (cookies if localstorage is not available).
Then on page load look for the scroll position from local storage if available and if so move to that position.
this work for readmore article or hide article, for get current position height of readmore clicked.
#note: you need toggle button readmore and hide
let readhide = document.querySelectorAll('.read-hide');
let readmore = document.querySelectorAll('.read-more');
readmore.forEach((more,key) => {
let height, moreHeight;
window.addEventListener('scroll', function(event){
height = Math.floor(event.target.scrollingElement.scrollTop);
});
more.addEventListener('click', function(){
moreHeight = height;
});
readhide[key].addEventListener('click', function(){
window.scrollTo(0, moreHeight);
});
});
Return Text
Try This.
<button onclick="goBack()">Go Back</button>
function goBack() {
window.history.go(-1);
}
I want a nav to highlight (or something similar) once a user clicks on it AND when a user scrolls to the corresponding section.
However, on my computer when one clicks on any of the nav events after3, only nav event 3 changes. I'm guessing this is because after one clicks on 4 or 5, the scroll bar is already at the bottom of the page, so 4 and 5 never reach the top. The only div at the top is post 3, so my code highlights nav event 3 and ignores the click.
Is there any way I can fix this? Ive tried if statements (only highlight nav event if it's at the top AND the scrollbar isn't at the bottom or the top isn't the last item).
Here is a more accurate fiddle, using a fix below showing what I am talking about. The fix now highlights on scroll, but if you click option 5, it will not highlight.
$('.option').children('a').click(function() {
$('.option').css('background-color', '#CCCCCC;');
$(this).css('background-color', 'red');
var postId = $($(this).attr('href'));
var postLocation = postId.offset().top;
$(window).scrollTop(postLocation);
});
$(window).scroll(function() {
var scrollBar = $(this).scrollTop();
var allPosts = [];
var post = $('.content').offset();
var lastPost = allPosts.legnth-1
var windowHeight = $(window).height();
var bottomScroll = windowHeight-scrollBar;
$(".content").each(function(){
allPosts.push($(this).attr('id'));
});
i = 0;
for(i in allPosts){
var currentPost = "#"+allPosts[i];
var postPosition = $(currentPost).offset().top;
if (scrollBar >= postPosition){
$('.option').css('background-color', '#CCCCCC');
$('#nav'+allPosts[i]).css('background-color', 'red');
};
};
});
I think you've overdone your scroll() handler, to keep it simple you just needs to check if the scrollbar/scrollTop reaches the '.contents' offset top value but should not be greater than its offset().top plus its height().
$(window).scroll(function () {
var scrollBar = $(this).scrollTop();
$(".content").each(function (index) {
var elTop = $(this).offset().top;
var elHeight = $(this).height();
if (scrollBar >= elTop - 5 && scrollBar < elTop + elHeight) {
/* $(this) '.content' is the active on the vewport,
get its index to target the corresponding navigation '.option',
like this - $('.Nav li').eq(index)
*/
}
});
});
And you actually don't need to set $(window).scrollTop(postLocation); because of the default <a> tag anchoring on click, you can omit that one and it will work fine. However if you are looking to animate you need first to prevent this default behavior:
$('.option').children('a').click(function (e) {
e.preventDefault();
var postId = $($(this).attr('href'));
var postLocation = postId.offset().top;
$('html, body').animate({scrollTop:postLocation},'slow');
});
See the demo.
What you are trying to implement from scratch, although commendable, has already been done by the nice folks at Bootstrap. It is called a Scrollspy and all you need to do to implement it is include Bootstrap js and css (you also need jquery but you already have that) and make some minor changes to your html.
Scrollspy implementation steps.
And here is a demonstration. Notice only one line of js. :D
$('body').scrollspy({ target: '.navbar-example' });