Can't scroll to dynamic element - javascript

Hey guys I'm having some issues scrolling to a an element that's dynamically created. You click on a search button, AJAX does its thing and updates the content. I have some code to dynamically find the ID and scroll to it. I am able to get the ID but I can't scroll to it. So far I have the code:
to_Scroll = $(this).closest('tr').attr('id');
$('html, body').animate({
scrollTop: $(to_Scroll).offset().top
}, 2000);
Which seems to work when I put it in the console with hard coded data. But doing it dynamically yields no results and no errors. Any help would be greatly appreciated
Below is some code which is done before I animate and scroll to an element:
dateChange(blah, blah2, blah3);
to_Scroll = $(this).closest('tr').attr('id');
$('html, body').animate({
scrollTop: $(to_Scroll).offset().top
}, 2000);
function dateChange(dateInput, nGuests, vName){
var promises = [];
var promise = $.ajax({
url: "/blah.asp?blah="+blah+"&blah2="+blah2+"&blah3="+blah3,
dataType:"html",
success: function(data){
table.html(data);
}
});
promises.push(promise);
$.when.apply($, promises).done(function() {
$( "#boatContent" ).removeClass( "loading" ); //Everything is done, remove loading gif
//do other stuff
}

to use ID again from attr you need to add # to it
$(document).ready(function(){
var to_Scroll = $(this).closest('tr').attr('id');
$('html, body').animate({
scrollTop: $( '#' + to_Scroll).offset().top
}, 2000);
});

Related

How to auto scroll to bottom with auto refresh in jquery

I am using this jquery ajax to receive msg from the database. But when someone trying to send a msg then it's coming here but could not auto scroll to the bottom. Any idea?
setTimeout(startRefresh,1000);
var myKeyVals = { some value };
var saveData = $.ajax({
type: 'POST',
url: "https://example.php",
data: myKeyVals,
success: function(resultData) {
$("#chatwindow").html(resultData);
//######################################
}
});
saveData.error(function() { alert("Something went wrong"); });
You can try something using animate & scrollTop inside ajax success like:
$("html, body").animate({
scrollTop: $(document).height() - $(window).height()
}, 'slow');
div {height: 900px; border:2px solid #333; padding:10px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv1">DATA FOR SAMPLE 1</div>
<div id="mydiv2">SAMPLE DATA</div>
<div id="mydiv2">SAMPLE DATA</div>
And to take care that new DOM elements are actually present before scrolling, you can try to add some setTimeout for few milliseconds and add this code inside it.
check this out: https://www.electrictoolbox.com/jquery-scroll-bottom/
The following Javascript will scroll the page to the bottom using jQuery:
$('html, body').animate({scrollTop:$(document).height()}, 'slow');
Obviously you can change the animation speed ('slow' in the above example) to something else such as 'fast' or a numeric duration in milliseconds where the higher the number, the slower the animation.
To bind the scrolling function to a click done on an existing element in the page, do something like this, where #someID is the element's ID:
$(document).ready(function() {
$('#someID').click(function(){
$('html, body').animate({scrollTop:$(document).height()}, 'slow');
return false;
});
});
You can try this trick. See if this helps you:
$("html, body").animate({ scrollTop: $(document).height() }, 20000);
setTimeout(function() {
location.reload();
},20000);

How to set focus/scrolltop to the first item in the loop?

I have a search form, when search button is clicked, it fetches data via ajax request and append into a div. Now, I need to automatically scrolltop to the first result of the search when items returned.How do I do that please?
script to set scrolltop:
$("#search").on("click",function(){
// Handler for .ready() called.
$('html, body').animate({
scrollTop: $('#view2').offset().top//instead of #View2, how do I make the page scrolltop to the first item appended in the for loop below?
}, 'slow');
});
When search button button clicked, results are fetched by ajax and appended into a div as below:
$("#searchform").on("submit", function () {
//$(this).find(':submit').attr('disabled','disabled');
var data = {
"action": "test"
};
$.ajax({
type: "POST",
dataType: "json",
url: "search/ajax2.php",
data: data,
success: function (data) {
$(".the-inner-return").append("<a href='search2.php?TID="+ tid +"'>")//need to set the scrolltop here
}
});
});
You can do in this way.
$("#search").on("click",function() {
$('html, body').animate({
scrollTop: $("#elementIdToWhichScroll").offset().top
}, 'slow');
});
Where elementIdToWhichScroll is your first element id.
EDIT CODE -
success: function (data) {
$(".the-inner-return").append("<a href='search2.php?TID="+ tid +"'>");
$('html, body').animate({
scrollTop: $("#elementIdToWhichScroll").offset().top
}, 'slow');
}
Use the following jQuery code
$( document ).ajaxComplete(function() {
$('html, body').animate({
scrollTop: $('#view2').offset().top//instead of #View2, how do I make the page scrolltop to the first item appended in the for loop below?
}, 'slow');
});
$("html, body").animate({ scrollTop: 0 }, "slow");
Use this code for after getting result data with your div id or class.
You need to move your animation into your ajax success callback. You can then use the :last pseudo to get the last anchor within that element (because you have appended it to the end, prepend would need :first).
http://jsfiddle.net/onj1yxdq/
success: function (data) {
$('.the-inner-return').append("<a href='search2.php?TID="+ tid +"'>");
$('html, body').animate({
scrollTop: $('.the-inner-return a:last').offset().top
}, 'slow');
}

Load page at specific point with jQuery (without animation!)

I want to load a page at a specific div on my page without animating to that point. Below is the code I'm using right now which animates to said div. I haven't been able to figure out how to do this same function without animation.
jQuery:
if(window.location.hash) {
var hash = window.location.hash;
var link = $("[href='"+ hash +"']");
if ( hash == "#specific-url" ) {
$('html, body').animate({
scrollTop: $("#specific-div").offset().top
}, 1000);
}
instead of this:
$('html, body').animate({
scrollTop: $("#specific-div").offset().top
}, 1000);
do this:
$(document).scrollTop($("#specific-div").offset().top);
In you code you were trying to animate the html,body of your document, so as you want to move at a specific location in your document i think you can directly set the .scrollTop() of your document the way i suggested to you above.
One way set animate time 0ms
if(window.location.hash) {
var hash = window.location.hash;
var link = $("[href='"+ hash +"']");
if ( hash == "#specific-url" ) {
$('html, body').animate({
scrollTop: $("#specific-div").offset().top
}, 0);
}
You can use
.scrollTop()
$(document).scrollTop($("#specific-div").offset().top);
.scrollIntoView()
$("#specific-div")[0].scrollIntoView(true);
or
document.getElementById(specific-div).scrollIntoView(true);

jquery scrolling won't scroll from exact location

I'm using the following jquery to make my links scroll to the next div. However, I've run into a problem. From the top of the page the script works fine. As soon as I click a link from another div (another link further down the page) the script only scrolls so far either up or down but not to the next specified div. How can I make the script scroll fully from the current location of where the link is located?
$(function() {
$('#nav a').bind('click',function(event){
var $anchor = $(this);
$('html, body, #container, .main').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500,'easeInOutExpo');
event.preventDefault();
});
});
You have a error here:
scrollTop: $($anchor.attr('href')).offset().top
//------^^^^^^^---------------------------------this itself a selector
change to this and try with:
scrollTop: $anchor.attr('href').offset().top
or this one too:
$('#nav a').bind('click',function(event){
var $anchor = $(this).attr('href');
$('html, body, #container, .main').stop().animate({
scrollTop: $($anchor).offset().top
}, 1500,'easeInOutExpo');
event.preventDefault();
});
CHECKOUT IN FIDDLE
You're not calling the correct spot...
this should do the trick... Set the anchor point first.
$(function() {
$('#nav a').bind('click',function(event){
var $anchor = $(this).attr('href');
$('html, body, #container, .main').stop().animate({
scrollTop: $($anchor).offset().top
}, 1500,'easeInOutExpo');
event.preventDefault();
});
});
ok, so I've made you a JSFiddle, the js-code I rewrote to the code below, but you can have a have a look at the full thing here: http://jsfiddle.net/re7Xc/
$(function() {
$('a.scrolltonext').click(function(event){
event.preventDefault();
var parentblock = $(this).parent();
var nextblock = parentblock.next();
//nextblock.css('background-color','#00f');
if(nextblock.size()>0) {
$('html, body').stop().animate({
'scrollTop': nextblock.offset().top
}, 800);
}
});
});
the catch in this script though is that I put the links in the div itself, so it's not in a #nav somewhere. So you'd have to rewrite that part if you put the links in your #nav!
I put an if-statement in there as well, because I thought it'd be better if you check if there is a next-div first, before scrolling there.
Hope it makes some sense, and let me know if it works for you!
cheers

Anchor Onclick Division Highlight

I have made a simple webpage with lots of division. So to navigate direct to a division I have put a anchor on top like this :
First<br/>
Second<br/>
Third
And for smooth scrolling I have used javascript:
$('a').click(function(){
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 500);
return false;
});
Now I want to add effect to the selected division. So when user click on an anchor, the page smoothly scrolls to the division and the selected division is highlighted for a second. Just like when we get any news in Stack Overflow inbox, and we click on it; the page lodes and the news item is highlighted for a short duration.
I want to do that thing to my page. Cause I'm having more then 18 divisions and they are all same.So it is necessary to differentiate the selected division.
Here is the example Fiddle : Fiddle For the Code
Any help would be appreciated. Thanks in advance.
In Your code $('html, body') returns 2 elements so animation will fire twice. If you include jquery.ui You will be able to do this:
$('a').click(function(){
var selector = $(this).attr('href');
$('html').animate({
scrollTop: $(selector).offset().top
}, 500,'',function(){
$(selector).effect("highlight", {}, 1000);
});
return false;
});
JsFiddle
This use opacity like example:
$('a').click(function(){
var el = $(this).attr('href');
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 500, function(){
$(el).animate({'opacity':0.5},200, function(){ $(el).animate({'opacity':1}, 200)} );
});
return false;
});

Categories

Resources