I have a modal window and need to be able to open the modal and then scroll the user to a specific spot in the modal.
I am getting the modal contents with AJAX to a PHP script.
eg mypage.php?loc=someid
In the PHP script I have this JS to do the scrolling:
$( document ).ready(function() {
$('.modal-body').animate({
scrollTop: $("#<?php echo $_GET['loc'];?>").offset().top
}, 1000);
});
in the PHP page is some HTML like this:
<div id="someid"></div>
My content loads correctly but the amount of scroll that happens appears to be relative to the link that opened the modal so it does not actually find the div in the doc.
I am guessing my JS needs a little tweaking.
It seems I need to be able to calculate the offset of the element from the top of the modal content.
I can fake this by setting the value against the element I am scrolling to like this. But I really need a programmatic way of calculating this. Obviously different devices will not work correctly as shown.
$( document ).ready(function() {
$('.modal-body').animate({
scrollTop: $("#<?php echo $_GET['loc'];?>").attr('distance')
}, 1000);
});
//Trying to find out how far this div is from the top of the modal window?
<div id="someid" distance="670"></div>
User found solution but doesn't appear to have added it, so for the sake of completeness, here it is
$( document ).ready(function() {
setTimeout(function() {
var $el = $("#<?php echo $_GET['loc'];?>")
var elpos = $el.position();
$('.modal-body').animate({
scrollTop: elpos.top
}, 1000);
},500);
});
The solution found by the OP and reposted by Rob Quincey works well, HOWEVER do remember that position give you the position relative to the element's parent element.
If the element is a bare <div> it is not problem, but if the grandparent element has some margin or padding properties, then the position of the parent element will be pushed down the page. Which means that the position of this element will also be pushed down. So to the the scrolling to work properly, you need to add the position of the parent element viz:
$( document ).ready(function() {
setTimeout(function() {
var $el = $("#<?php echo $_GET['loc'];?>")
var elpos = $el.position();
var elparentpos = $el.parent().position();
$('.modal-body').animate({
scrollTop: elpos.top + elparentpos.top;
}, 1000);
},500);
});
And then, if necessary, work your way up the DOM tree until you get to the top element which would normally be your modal div. But you only need to address elements which have some top end margin or padding.
Related
I have the following code which works exactly as I need for refreshing a page using a submit button.
However I have added code in it to make it scroll down to a specific location after updating, the problem is, it scrolls down to the location, then springs back to the top of the page
any ideas why anybody please?
$(".visitpage").on('click', function() {
$('body').append('<div style="" id="loadingDiv"><div class="loader"></div><center><span style="font-size:22px;color:#000000;z-index:99999;"><b>Updating your results...</b></span></center></div>');
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
$('html, body').animate({
scrollTop: $("#search-results").offset().top
}, 2000);
});
function removeLoader() {
$("#loadingDiv").fadeOut(500, function() {
// fadeOut complete. Remove the loading div
$("#loadingDiv").remove(); //makes page more lightweight
});
}
You will surely need the scrollTo method of the window object in javascript. Then I would figure out how far down your element is by getting a reference for that object in pixels on the page. See Retrieve the position (X,Y) of an HTML element for how to do that, since part of your answer would be a duplicate question I will let you read it. And this article is helpful http://javascript.info/coordinates
window.scrollTo(500, 0);
https://www.w3schools.com/jsref/met_win_scrollto.asp
Maybe I'm wrong here; but if you created a div where you want the page to scroll, or if you have on there make sure it's named, then right after the refresh command add
window.location.href = "#YOURDIVTAGHERE"; so
So if this is the part of the page you want it to go down to:
<div id="search-results">
CONTENT
</div>
so then your JS code, maybe try:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$(".visitpage").on('click', function(){
$('body').append('<div style="" id="loadingDiv"><div class="loader"></div><center><span style="font-size:22px;color:#000000;z-index:99999;"><b>Updating your results...</b></span></center></div>');
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
});
function removeLoader(){
$( "#loadingDiv" ).fadeOut(500, function() {
// fadeOut complete. Remove the loading div
$( "#loadingDiv" ).remove(); //makes page more lightweight
});
window.location.href = "#search-results";
}
Consider the following snippet:
<div id="help"></div>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
var loadPage = function (){
$("#help").load("http://localhost:3000/manual.html");
}
onload=loadPage;
</script>
This exists on my main page:
http://localhost:3000/
The above code works fine and loads my manual page. But if I click a link like this in manual.html:
<a href='#introduction'>Introduction</a>
Then the page in the help div jumps to the #introduction section, however the url in my browser updates to:
http://localhost:3000/#introduction
This is pointless because the #introduction anchor only exists in manual.html, how can I prevent the links in the #help div from affecting the address bar in the browser?
Try this
$('a').click(function(e) {
e.preventDefault();
$("#help").load($(this).attr('href'));
})
By using offset and preventDefault
$('a').click(function(e) {
// Go to '#introduction'
var targetId = $(this).attr('href');
$('html, body').offset({ top: $(targetId).offset().top, left: 0 });
// this prevent 'http://localhost:3000/#introduction'
e.preventDefault();
});
See this post
I already had a function that could scroll the #help window to a heading, when you click on objects in the parent it scrolls to the relevant section in the help window:
var moveTo = function(destination){
//position of the top of the help window - does not change.
var helpWindow = $("#help").offset().top;
//difference between current scroll position and target position.
var relativeDistance = $(destination).position().top - helpWindow;
//add the distance from current position to the top to get distance to target from top
var absoluteDistance = relativeDistance+ $("#help").scrollTop();
$("#help").animate({
scrollTop: absoluteDistance
}, 1000);
}
Using e.preventDefault() I was able to use this function to do what I want.
For others heading down this path there are two other small things to consider.
Firstly, make sure you nest the .click() function inside the callback from page load, as the hyper links won't exist until the page is loaded. Secondly, You will probably want to use a child selector eg $('#help a').click() to ensure you are only altering the behaviour on links inside the child.
$("#help").load("http://localhost:3000/manual.html", function(){
$('#help a').click(function(e) {
e.preventDefault(); //suppress standard link functionality
moveTo($(this).attr('href')); //scroll to link instead.
})
});
I am new to jQuery, I built this page and what I would like to happen is when a block e.g. 2011 1 October reaches the top of the page it displays the content for that specific div via the id or date-attr.
When you click on a date it will display the content for that date but I would like it to appear once that date block reaches the top of the page.
I have looked around the net but no luck thus far.
Use scroll event to make checks for divs you are interested in - assing class for them for instance.
http://api.jquery.com/scroll/
In that event callback you can check each elements position
http://api.jquery.com/each/
To determine position element on page use
http://api.jquery.com/offset/ - top component
But don't take this value - you need to substract Window scroll position which is returned by
$(window).scrollTop()
And make some border values when element should be opened and when closed.
As per your description that I understood, you will have to add one line of code to your "main.js" file.
// javascript + jquery scripts
// script for fading in content boxes -->
$(".square").on("click", function() {
var id= $(this).attr("contentId");
//$("#details");
$('#details').fadeOut('slow', function() {
$(this).html($("#" + id).html()).fadeIn('fast');
});
});
// active link -->
$(".square").click(function() {
$(".square").removeClass("active");
$(this).addClass("active");
$("html, body").scrollTop($(this).position().top); // THIS IS THE LINE TO BE ADDED TO SCROLL TO THE CURRENT DATE ITEM
});
// fade in main content div / intro
$(document).scroll(function () {
var y = $(this).scrollTop();
if (y > 10) {
$('.topBlock').fadeOut();
} else {
$('.topBlock').fadeIn();
}
});
// hide intro text onClick on list
$( "li" ).click(function() {
$( ".topBlock" ).hide().animate();
});
var viewportHeight = $(window).height();
//$j(".parallax_section_holder").css("height",$j(window).height()-116);
//alert(viewportHeight);
I hope I have solved your issue, and if not, then please provide me the exact code link in jsfiddle.
Regards.
I have the following html structure repeated multiple times on a page:
<div class="item">
<div class="header">
...
Close All Expanded
</div>
<div class="expanded">
...
</div>
</div>
And some jQuery to close all the divs with class expanded when the link is clicked:
$('.closeExpanded').click(function(e){
e.preventDefault();
$('.expanded').slideUp('slow');
});
However I want to ensure that the link you've just clicked remains in view and moves as little as possible. Currently clicking on a link halfway down the page causes the link to move up out of the viewport as divs above it are closed.
Is there a nice graceful way I can keep the link that's been clicked in the viewport?
Update:
I've tried the answers suggested so far but so far none completely work (e.g. clicking link number 30 in each of these leads to link number 30 ending up outside of the viewport)
mrtsherman's solution: http://jsfiddle.net/Qan5p/38/
Mohsen's solution: http://jsfiddle.net/Qan5p/39/
roXon's solution: http://jsfiddle.net/Qan5p/40/
You will need to modify the scrollTop property of the page to keep things in place. Fortunately, as elements are shrunk they will be triggering scroll events you can hook into.
//untested, but should look something like this
var linkPosition = null;
$('.closeExpanded').click(function(e){
e.preventDefault();
linkPosition = $(this).offset().top - $(document).scrollTop();
//in callback to slideUp clear linkPosition so that we know to stop tracking scroll events
$('.expanded').slideUp('slow', function() {
linkPosition = null;
});
});
$(document).scroll( function(){
//check to see if we should be keeping link on screen
if (linkPosition != null) {
//keep the link in position
//I'm not so sure about this bit of the code, but I think you get the idea. All you have to do
//is properly calculate the new offset to keep the link looking like it is in the same position
var newPos = $(document).scrollTop() + linkPosition;
$(document).scrollTop(newPos);
}
});
$('.closeExpanded').click(function(e){
e.preventDefault();
$('.expanded').css({
'position' : 'absolute', // make it position absolute to prevent moving
'left' : $(this).offset().left,
'top' : $(this).offset().top
}).slideUp('slow', function(){
$('.expanded').css('position', 'static');
});
});
Fiddle: http://jsfiddle.net/mohsen/Qan5p/10/
WORKING DEMO
The easiest way:
Wrap contents into dynamically generated divs.
First animate the contents,
Than animate the wrapper elements
$('.expanded').wrapInner('<div class="wrapper" />');
$('.expanded').each(function() {
$(this).height($(this).children('.wrapper').height());
});
$('.closeExpanded').click(function(e) {
e.preventDefault();
$('.wrapper').animate({height: '0px'}, 800, function() {
$('.expanded').slideUp(800);
});
});
Whenever the url contains the div id, it would obviously go down to the div when the URL has:
http://domain.com.faq.php#1
<div id="1">Bla bla bla</div>
But what I like is to have same feature of Stackoverflow, when you click on an answer in your messages, it will scroll down to the page and has that fadeOut effect on the answer.
How do I do this?
Animation to a valid anchor destination cannot be animated on page load that I know of since the browsers will default to scrolling the user down the page to the anchor. For in-page links, you can hijack the anchor links and animate.
However, on new page loads like on SO, you will notice the page does not animate down, but just scrolls down, though the box does animate a color. This is how you could do it in jQuery. Be sure to include the color plugin if you want to animate background-colors.
<script src="js/jquery.color.js"> </script>
<script type="text/javascript">
$(window).load(function(){
var hash = window.location.hash;
if(hash){
$(hash).css('backgroundColor', '#AA0000')
.animate({backgroundColor: '#FFFFFF'}, 200);
}
});
</script>
You can use DOMReady instead of load, but it might try to run your animation too soon, and the user will miss it.
If you only wanted to animate div's with a specific class, you can add a filter to your find:
$(hash).filter('.my_div').css ...
Use:
event.preventDefault();
For example:
$('li.share a').click(function(ev) {
ev.preventDefault();
var link = ev.target.href;
var id = link.substring(link.indexOf("#") + 1);
$('#' + id).fadeOut();
});
StackOverflow uses anchors as well. The post you're currently reading is:
HTML and jQuery anchoring
It's simply <a name="anchorName"></a>
at the address bar: [urlToPage]#anchorName
Now, to get the fade effect [in pure JS w/o frameworks]
Set the div.style.opacity = 0;
var intervalId = setInterval( function(){
if( (div.style.opacity+= 0.1) >= 1) clearInterval(intervalId);
}, millisecondInterval);
The clearInterval part isn't necessary, since once opacity goes above 1, browser won't render differently [although the number keeps adding...]