I am using a div refresh script (Given below). The contents of the div contains an auto scroll ul (code from http://www.dynamicdrive.com/). The refresh is working properly. But after the refresh the auto scrolling is not working
Code for refresh
<script type="text/javascript">
window.onload = setupRefresh;
function setupRefresh()
{
setInterval("refreshBlock();",1000);
}
function refreshBlock()
{
$('#list4').load("refreshpage");
}
</script>
Code for auto scroll
<script type="text/javascript">
var delayb4scroll=2000 //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=1 //Specify marquee scroll speed (larger is faster 1-10)
var pauseit=1 //Pause marquee onMousever (0=no. 1=yes)?
var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var actualheight=''
function scrollmarquee(){
if (parseInt(cross_marquee.style.top)>(actualheight*(-1)+8))
cross_marquee.style.top=parseInt(cross_marquee.style.top)-copyspeed+"px"
else
cross_marquee.style.top=parseInt(marqueeheight)+8+"px"
}
function initializemarquee(){
cross_marquee=document.getElementById("vmarquee")
cross_marquee.style.top=0
marqueeheight=document.getElementById("list4").offsetHeight
actualheight=cross_marquee.offsetHeight
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
cross_marquee.style.height=marqueeheight+"px"
cross_marquee.style.overflow="scroll"
return
}
setTimeout('lefttime=setInterval("scrollmarquee()",30)', delayb4scroll)
}
if (window.addEventListener)
window.addEventListener("load", initializemarquee, false)
else if (window.attachEvent)
window.attachEvent("onload", initializemarquee)
else if (document.getElementById)
window.onload=initializemarquee
</script>
Could some one please help?
It seems like you need to call initializemarquee() after the load is complete. You can do this in the .load()'s callback.
function refreshBlock(){
$('#list4').load("refreshpage", function(){
clearInterval(lefttime);
initializemarquee()
});
}
I almost forgot to add that you'd also want to stop that interval.
You just need:
function refreshBlock()
{
$('#list4').load("refreshpage");
initializemarquee();
}
Why the mix of plain JS and jQuery? If you have jQuery use it
Here is my rewrite. Not tested but apart from typos or things that I thought could be done in jQuery and cannot, it should do the whole thing
$(function() {
var sId = setInterval(function {
$('#list4').load("refreshpage");
},1000);
var $cross_marquee=$("#vmarquee")
var delayb4scroll=2000 //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=1 //Specify marquee scroll speed (larger is faster 1-10)
var pauseit=true //Pause marquee onMousever (false=no. true=yes)?
var copyspeed=marqueespeed;
var pausespeed=(pauseit==0)? copyspeed: 0;
var actualheight=$cross_marquee.height();
var marqueeheight=$("#list4").height();
$cross_marquee.top(0);
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
$cross_marquee.height(marqueeheight);
$cross_marquee.css("overflow","scroll");
}
else var tId = setTimeout(function() {
lefttime=setInterval(
function() {
var top = $cross_marquee.top();
if (top>(actualheight*(-1)+8)) $cross_marquee.top(top-copyspeed)
else $cross_marquee.top(marqueeheight+8);
}
},30)
, delayb4scroll);
});
Related
I am doing a blog with PHP, AJAX, MySQL, etc. As usual, each post has its ID and inside the posts you can see the comments.
What I am trying to do is refresh the comment's div by calling the comments.php document with AJAX and putting it in the div with $('#comments').html(data);.
Doing this every 5 seconds for maintaining the comments like in real time, but the problem is that when the div does the first refreshing, the div loses the ID of the post and say that is undefined.
How can I refresh any div without losing the ID of the post?
If I call the comments.php file with the typical include(file.php) inside of the post file, I have no problem, but using this way I just can't refresh the content.
Here's the code:
post.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'support/comments.php',
success: function(data) {
$('#comments').html(data);
}
});
});
</script>
div where the result is going to be showed:
<div id="comments">
</div>
Script for refreshing the div:
<script language="Javascript" type="text/javascript">
function refreshDivs(divid, secs, url) {
// define our vars
var divid,secs,url,fetch_unix_timestamp;
// The XMLHttpRequest object
var xmlHttp;
try {
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("your browser doesn't support ajax.");
return false;
}
}
}
// Timestamp para evitar que se cachee el array GET
fetch_unix_timestamp = function () {
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// the ajax call
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout(function(){refreshDivs(divid,secs,url);},secs*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
window.onload = function startrefresh () {
//update content on real time
refreshDivs('comments',10,'support/comments.php');
}
</script>
You can pass the post id in the URL, like so:
url: 'support/comments.php?id=<?= $post_id ?>'
Then wrap the call with a setTimeout, like so:
window.setInterval(function(){
$.ajax({
url: 'support/comments.php?id=<?= $post_id ?>',
success: function(data) {
$('#comments').html(data);
}
});
}, 5000);
And discard refreshDiv.
This is assuming that comments.php retrieves the comments, and some other code posts them.
ok guys I solved it... I am gonna leave the code here in case of somebody could has the same problem... what I did was build a hidden input and put this input to use its value like the id of the post, then I sent the value of this input to the script with #('div').val and finally I sent that value to the comments.php file, once there.... I used the value in the query sentence for doing the comparative and finally can get the comments in the right post
Here's the code
<script>
$(document).ready(function() {
window.setInterval(function(){
//Comentarios
var id = $("#idcomment").val();
$.get("support/comments.php", { idpost: id }, function(LoadPage){
$("#comment").html(LoadPage);
});
}, 5000);
});
</script>
on http://zentili.koding.com i've got this javascript that loads the content of the linked menu item inside the main #content div of the index page, and applies an hash with the name of the loaded page minus the '.php', otherwise it loads the hash + '.php' if it's entered in the url. works very good. On other hand, the ENG/ITA entries add ?locale=lang_LANG inside the url, right before the hash, so that localization is also working fine. If you look well, you may notice that when you switch between ENG and ITA, the index-content appears just for one moment before going to the hash. I know this is because the page is first loaded, then taken to the hash but i was wondering if there some way for hiding the homepage and going directly to the hash location when it's loaded.
Here the code for my menu:
<script type="text/javascript">
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('#menubar a.item').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-4)){
var toLoad = hash+'.php';
$('#content').load(toLoad);
$("#menubar a.item").removeClass("current");
$(this).addClass("current");
}
});
$('#menubar a.item').click(function(){
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-4);
var toLoad = $(this).attr('href');
$('#content').fadeOut('fast',loadContent);
function loadContent() {
$('#content').load(toLoad,'',showNewContent) }
function showNewContent() {
$('#content').fadeIn('fast'); }
$("#menubar a.item").removeClass("current");
$(this).addClass("current");
return false;
});
});
function goENG(){
var hash = window.location.hash;
var eng = '?locale=en_EN';
window.location.replace(eng+hash) ;
};
function goITA(){
var hash = window.location.hash;
var ita = '?locale=it_IT';
window.location.replace(ita+hash) ;
};
</script>
the functions goENG() and goITA() are called via onclick on the ENG and ITA a's. I hope to find some solution into this.
The page cannot directly go to the link. It will load in its natural order and then it will go to the hash. For what you want to achieve, there is a simple solution i believe.
Hide the main content div until the document loads. use css rule "visibility:hidden" for this
If there is any hash, load it and then make the content visible.
If there is no hash in url, make the content visible on dom load.
$(document).ready(function() {
var hash = window.location.hash.substr(1);
if ($('#menubar a.item').length > 0) {
var href = $('#menubar a.item').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-4)){
var toLoad = hash+'.php';
$('#content').load(toLoad, function(){
$('#content').attr('visibility', 'visible');
});
$("#menubar a.item").removeClass("current");
$(this).addClass("current");
} else {
$('#content').attr('visibility', 'visible');
}
});
} else {
$('#content').attr('visibility', 'visible');
}
});
--UPDATE--
If you are setting #content as "visibility:hidden"
$('#content').attr('visibility', 'visible');
should always fire, else your #content div will be invisible. The trick here is to set it to visible after we are done with checking for hash. You can keep loading the content in the div and make it visible. Making the #content div visible need not be done after entirely loading the hash.
I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was just on?
I realized that I had missed the important part of submitting, so, I decided to tweak the code to store the cookie on click event instead of the original way of storing it while scrolling.
Here's a jquery way of doing it:
jsfiddle ( Just add /show at the end of the url if you want to view it outside the frames )
Very importantly, you'll need the jquery cookie plugin.
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When a button is clicked...
$('#submit').on("click", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
Here's still the code from the original answer:
jsfiddle
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When scrolling happens....
$(window).on("scroll", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
#Cody's answer reminded me of something important.
I only made it to check and scroll to the position vertically.
(1) Solution 1:
First, get the scroll position by JavaScript when clicking the submit button.
Second, include this scroll position value in the data submitted to PHP page.
Third, PHP code should write back this value into generated HTML as a JS variable:
<script>
var Scroll_Pos = <?php echo $Scroll_Pos; ?>;
</script>
Fourth, use JS to scroll to position specified by the JS variable 'Scroll_Pos'
(2) Solution 2:
Save the position in cookie, then use JS to scroll to the saved position when page reloaded.
Store the position in an hidden field.
<form id="myform">
<!--Bunch of inputs-->
</form>
than with jQuery store the scrollTop and scrollLeft
$("form#myform").submit(function(){
$(this).append("<input type='hidden' name='scrollTop' value='"+$(document).scrollTop()+"'>");
$(this).append("<input type='hidden' name='scrollLeft' value='"+$(document).scrollLeft()+"'>");
});
Than on next reload do a redirect or print them with PHP
$(document).ready(function(){
<?php
if(isset($_REQUEST["scrollTop"]) && isset($_REQUEST["scrollLeft"]))
echo "window.scrollTo(".$_REQUEST["scrollLeft"].",".$_REQUEST["scrollTop"].")";
?>
});
Well, if you use _targets in your code you can save that.
Or, you can do an ajax request to get the window.height.
document.body.offsetHeight;
Then drop them back, give the variable to javascript and move the page for them.
To Remember Scroll all pages Use this code
$(document).ready(function (e) {
let UrlsObj = localStorage.getItem('rememberScroll');
let ParseUrlsObj = JSON.parse(UrlsObj);
let windowUrl = window.location.href;
if (ParseUrlsObj == null) {
return false;
}
ParseUrlsObj.forEach(function (el) {
if (el.url === windowUrl) {
let getPos = el.scroll;
$(window).scrollTop(getPos);
}
});
});
function RememberScrollPage(scrollPos) {
let UrlsObj = localStorage.getItem('rememberScroll');
let urlsArr = JSON.parse(UrlsObj);
if (urlsArr == null) {
urlsArr = [];
}
if (urlsArr.length == 0) {
urlsArr = [];
}
let urlWindow = window.location.href;
let urlScroll = scrollPos;
let urlObj = {url: urlWindow, scroll: scrollPos};
let matchedUrl = false;
let matchedIndex = 0;
if (urlsArr.length != 0) {
urlsArr.forEach(function (el, index) {
if (el.url === urlWindow) {
matchedUrl = true;
matchedIndex = index;
}
});
if (matchedUrl === true) {
urlsArr[matchedIndex].scroll = urlScroll;
} else {
urlsArr.push(urlObj);
}
} else {
urlsArr.push(urlObj);
}
localStorage.setItem('rememberScroll', JSON.stringify(urlsArr));
}
$(window).scroll(function (event) {
let topScroll = $(window).scrollTop();
console.log('Scrolling', topScroll);
RememberScrollPage(topScroll);
});
I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
$(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
}
$(window).on("scroll", function() {
localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
});
});
</script>
I tackle this via using window.pageYOffset . I saved value using event listener or you can directly call window.pageYOffset. In my case I required listener so it is something like this:
window.addEventListener('scroll', function() {
document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px';
})
And I save latest scroll position in localstorage. So when next time user comes I just check if any scroll value available via localstorage if yes then scroll via window.scrollTo(0,myScrollPos)
sessionStorage.setItem("VScroll", $(document).scrollTop());
var scroll_y = sessionStorage.getItem("VScroll");
setTimeout(function() {
$(document).scrollTop(scroll_y);
}, 300);
I have a gallery in my website (on my computer, not on a server yet) and I have a problem on it. here is it's script(it's loaded from the server by php):
$(document).ready(function() {
$('.gallery').hide();
$('.gallery:first').fadeIn();
var galleryItems=$('.gallery').length;
var index=0;
setInterval(function()
{
index++ ;
var id="gallery-"+(index);
$('.gallery').hide();
if (index==galleryItems)
{
index=0;
}
$('#gallery-'+index).fadeIn(1000);
},7000);
});
The gallery works, but after some time that I'm not looking on the gallery it stop working correctly.
This is how it supposed to look:
picture 1
This is how it actually looks:
picture 2
What should I do?
I believe that when the index==galleryItems you are fading in item 0 instead of the last item. Then when the gallery continues it fades in the next item, resulting in doubling.
$(document).ready(function() {
$('.gallery').hide();
$('.gallery:first').fadeIn();
var galleryItems=$('.gallery').length;
var index=0;
setInterval(function()
{
index++ ;
//var id="gallery-"+(index); this is unused so it should be removed.
$('.gallery').hide();
$('#gallery-'+index).fadeIn(1000); // MOVED TO BEFORE INDEX RESET
if (index==galleryItems)
{
index=0;
}
},7000);
});
I have a pinterest style site and made a jquery script that spaces the cubes evenly no matter how big the browser is. For some reason on page load it has some overlapping cubes which didn't exist before. I talked with the guy that helped me make it and he said it's probly because of the code before the code that creates the blocks and positions them. It crashes the javascript.
I think it's because of the $(window).scroll ajax loading code but I can't seem to pinpoint the problem. I tried moving positionBlocks(); around and nothing changes. If you load the page in your browser and then change your browser size then it positions them correctly but obviously I want it to look right when the user first gets there.
function setupBlocks() {
windowWidth = $(window).width();
blocks = [];
// Calculate the margin so the blocks are evenly spaced within the window
colCount = Math.floor(windowWidth/(colWidth+margin*2));
spaceLeft = (windowWidth - ((colWidth*colCount)+margin*2)) / 2;
spaceLeft -= margin;
for(var i=0;i<colCount;i++){
blocks.push(margin);
}
positionBlocks();
}
function positionBlocks() {
$('.block').each(function(i){
var min = Array.min(blocks);
var index = $.inArray(min, blocks);
var leftPos = margin+(index*(colWidth+margin));
$(this).css({
'left':(leftPos+spaceLeft)+'px',
'top':min+'px'
});
blocks[index] = min+$(this).outerHeight()+margin;
});
}
// Function to get the Min value in Array
Array.min = function(array) {
return Math.min.apply(Math, array);
};
var curlimit=<?php echo $curlimit; ?>;
var totalnum=<?php echo $num_rws; ?>;
var perpage=<?Php echo $perpage ?>;
var working_already=false;
$(document).ready(function() {
//($(window).scrollTop() + $(window).height() )> $(document).height()*0.8
// old ($(window).scrollTop() + $(window).height() == $(document).height())
$(window).resize(setupBlocks);
$(window).scroll(function() {
if(($(window).scrollTop() + $(window).height() )> $(document).height()*0.90 && totalnum>0 && working_already==false ) {
} else return false;
working_already=true;
$("div#loading_bar").fadeIn("slow");
curlimit=curlimit+perpage;
$("div#loading_data_location").html("");
$.get('get_cubes.php?page=<?php echo $_GET['page'] ?>&curlimit='+curlimit, function(response) {
$("div#loading_data_location").html(response);
$("div#ColumnContainer").append($("div#loading_data_location").html());
$("a#bigpic").fancybox({
'onComplete' : imageLoadComplete,
'onClosed' : imageClosed,
'type': 'ajax' });
if ($("div#loading_data_location").text()=="")
totalnum=0;
else
totalnum=<?php echo $num_rws; ?>;
$('.like:not(.liked)').click(like_box);
$('.save:not(.saved)').click(save_box);
$('.follow:not(.following)').click(follow);
$("div#loading_bar").fadeOut("fast");
$("div#loading_data_location").html('');
setupBlocks();
working_already=false;
});
});
I had to add this to the end of my script:
<script language="javascript">
$(window).bind("load", function() {
setupBlocks();
});
</script>
and then this to the end of the on scroll ajax load. Sometimes jquery just needs a little kick in the face haha:
setTimeout(function(){setupBlocks();},100);