I've a servlet that prints html pages. I would like that those pages auto cicling using a js script. So I load an html page, after 3 second it refresh and I load another html page (printed by the same servlet).
In the servlet:
- read the session where I store the index of the page i'm printing;
- basing on this index, I print the page and I update the index (it increase or it return to 0 if I'm printing last page)
- store the index in a div element, so I can find it by javascript function and refresh the html page with a js function
out.println("<div id=\"storedDiv\">");
int indexRefresh= (int) request.getSession().getAttribute("indexRefresh");
out.println(Integer.toString(indexRefresh) );
indexRefresh=indexRefresh+1;
if (indexRefresh==Tot) {
indexRefresh=0;
}
request.getSession().setAttribute("indexRefresh", indexRefresh);
out.println("</div>");
The js function find the div element in the html page and update the page
function refresh(){
var element = document.getElementById("storeDiv");
if (element==0){
setTimeout(function() {
window.location.href = "http://localhost:9080/HydroGui/Query?anno=2018&id=1";
}, 3000);
}
if (element==1){
setTimeout(function() {
window.location.href = "http://localhost:9080/HydroGui/Query?anno=2018&id=2";
}, 3000);
}
}
But where have I call the function? if I use the
window.onload = refresh();
page load before I stored the index in the div.
So what is the best method to do this?
Use innerHTML
var element = document.getElementById("storeDiv").innerHTML;
if (element == '0') {
//...
}
Related
What I'm trying to do exactly
I'm creating a custom WordPress site, it displays a "load more posts" button in the pages blog (main), category and search results. When the user clicks this button, the script retrieves the posts in the next page and appends them inside a container. Here's the code:
<script>
document.addEventListener("DOMContentLoaded", function() {
// display or not the btn when page is loaded
var morePosts = $("#dom-target").text();
if (morePosts != "true") {
$('.load-more').css('display','none');
}
// button functionality
var pageIndex = 1;
var numOfPages = Number($('#numOfPages').text()); // parsed from php
var nextLink = $('#nextLink').text(); // parsed from php
$('.load-more').click(function(){
if (pageIndex < numOfPages) {
var nextPosts;
$.get(nextLink+' .post-card', function(data){
// get articles in next page
nextPosts = data;
// append articles
$('#content').append(nextPosts);
// change value of index and redefine nextLink
pageIndex++;
nextLink = nextLink.replace(pageIndex+'/',pageIndex+1+'/');
// check if button display is still needed
if (pageIndex == numOfPages) {
$('.load-more').css('transition','all 0s');
$('.load-more').fadeOut();
}
});
}
});
});
</script>
The problem: It loads the entire page
I wonder if $.get() has a equivalent for .load('main url .specific-class'), because when I try to apply the analogous syntax
$.get(nextLink+' .post-card')
the console threw me
GET http://localhost/blog/page/2/%20.post-card 404 (Not Found)
Or if there is a way to parse the data (a string) as an HTML document (so I can apply jQuery to the variable that stores the data and get just the post cards instead of the entire page).
Thanks in advance! :)
You have to parse the response yourself which you can do simply by wrapping in $() and using any jQuery method on
$.get(nextLink, function(data){
var nextPosts = $(data).find('.post-card');
$('#content').append(nextPosts);
//.......
});
I've written a Javascript function that loads paginated content onto a page as you scroll to the bottom. The goal of this function is to increment the page number as you scroll and add that specific page number to the content already displayed, like Facebook does.
$(document).ready(function() {
$(window).scroll(function() {
var pagenumber = document.getElementById("pagenumber");
var results_box = document.getElementById("results_box");
var combo = pagenumber.innerHTML.split("|");
var pn = parseInt(combo[0]);
var last = parseInt(combo[1]);
results_box.innerHTML = "";
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
// ajax call get data from server and append to the div
results_box.innerHTML = "Loading...";
if (last != 1) {
if (pn < last) {
request_page(pn + 1);
} else if (pn == last) {
pagenumber.innerHTML = pn + 1 + "|" + last;
request_page(last);
} else {
results_box.innerHTML = "No More Content available";
}
}
}
});
});
the ajax "loading..." code not fire but when it randomly does it might load just two pages or duplicate some. My conjecture is that is has to do with the lack of a timestamp on each request for a new page.
The request_page function is fired once before the page is loaded, to display the first page of code, and the pagination "next" button when clicked accurately adds new content to the page,so my question is, how would i incorporate a timestamp into this function to effectively load data onto a page?
For clarity there is a div that displays the page number you're on out of total pages ex. 1 | 3 , the "last" variable is the last page ( 3 ) and the "pn" page number variable is the current page (1)
In a web page I refresh/reload a div, every minute, with content which is in a text file. This part of the code is working.
The problem is that in the table, when I have severals lines with in the first column have the same content, I need to concatenate it.
Example that I want:
Example that I have after the table data reload:
Here the code in order to reload my table/div every minute:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#datatable-1_wrapper').load('bodytest.txt');
//part of code that worked when i load the entire page, but not work in this setInterval method
var names = {}, td, cname, p;
$('#t1').find('tr').each(function(){
if((td = $(this).find('td').get(0)) && (cname = td.className)){
var cnames = cname.split(' ');
names[cnames[0]] = names[cnames[0]]? names[cnames[0]] + 1 : 1;
}
});
for (p in names){
if(names[p] > 1){
$('.' + p + ':gt(0)').remove();
$('.' + p).attr('rowspan', names[p]);
}
}
}, 10000);
});
Can you explain me why the part of the code which concatenate the lines in one td is working when i load the page but not in the refresh method?
Thanks
Just guessing here, but it looks like your code runs too soon; consider this instead:
$('#datatable-1_wrapper').load('bodytest.txt', function() {
// loaded, now do the rest of your code
});
The inner function will get called once the wrapper has been loaded.
I have a list of products say:
laptops/prod1.html
laptops/prod2.html
laptops/prod3.html
monitors/prod1.html
monitors/prod2.html
monitors/prod3.html
I would like a button on my page that 'cycles' through the available items.
No idea how to do this. Is this possible with javascript?
function nextProduct(incr) {
var href = window.location.href
, offset = (typeof(incr)==='undefined' ? 1 : incr);
window.location = href.replace(/(\d+)\.html/, function(m, g1) {
return (Number(g1) + offset) + '.html'
});
}
Then you can do something like:
var button;
button = document.getElementByID('next-button');
button.addEventListener('click', function() { nextProduct(1); });
button = document.getElementByID('prev-button');
button.addEventListener('click', function() { nextProduct(-1); });
Setup a main page, this should not be a static html page but in your server side language of choice.
Include jquery to a main page using a script tag (you can get jquery from http://jquery.com/).
Your html could look like this:
<div id='content'></div>
<div>
<a href='javascript:void(0)' id='prev' class='btn'>Previous</a>
<a href='javascript:void(0)' id='next' class='btn'>Next</a>
</div>
In your js file you would have something like this:
var currPage = 0;
var pageList = ["laptops/prod1.html","laptops/prod2.html", "laptops/prod3.html"];
var totalPages = pageList.length;
$(".btn").on("click",function(){
//if we are at the last page set currpage = 0 else increment currPage.
currPage = currPage < (totalPages - 1) ? ++currPage : 0;
var page = pageList[currPage];
$('#content').load(currPage);
});
Some points to consider:
You will want to decide if the first page gets loaded on the main page load or on click
You will need to set a js variable to keep track of the currently loaded page
You will need to add some method of storing all the possible pages (think an array). This can get printed out to a script tag on the page on page load.
You need to decide what happens when you hit the end of the line. You can either cycle around or grey out the appropriate link.
jquery on
jquery load
The javascript of the div "intro" is loading at last. It's taking too long to load as the web page loads the bg image first and then loads the java script. Is there a way i can display "loading please wait" message in that "intro" div until it completely loads. I just want that the intro should load first.
Javascript code:
var tl = new Array(
"=======================",
" Welcome user, ",
" ###########################################"
);
var speed = 50;
var index = 0;
text_pos = 0;
var str_length = tl[0].length;
var contents, row;
function type_text() {
contents = '';
row = Math.max(0, index - 20);
while (row < index)
contents += tl[row++] + '\r\n';
document.forms[0].elements[0].value = contents + tl[index].substring(0, text_pos) + "_";
if (text_pos++ == str_length) {
text_pos = 0;
index++;
if (index != tl.length) {
str_length = tl[index].length;
setTimeout("type_text()", 500);
}
}
else setTimeout("type_text()", speed);
}
This is the script and its basically typing letter by letter in a text area in the div "intro". The problem is that it loads at last when the whole page has loaded. It starts printing the text after like 15 seconds or so.
There are "domready" events you can listen to on the document but seems that's not cross-browser.
Eg: Mozilla
document.addEventListener("DOMContentLoaded", methodName, false)
A better option is to use jQuery's .ready() event. They handle all cross-browser implementations.
Eg:
$(document).ready(function(){
//execute code here
});
//Shorthand
$(function(){
//...
});
See this related question for more on domready.
Load a page with the empty intro div, run the script with "loading please wait" then trigger an ajax request to load the rest of the page and update the page on onComplete event from the ajax request
Using jQuery
$(document).ready(function() {
// update div here
});
http://api.jquery.com/ready/
Or you could do that with
window.onload= (function() {
// update div here
};
You can use jquery for this by wrapping the content in a div tag and then another div that holds a loading image, something to this effect:
$(document).ready(function () {
$('#loading').show();
$('#divShowMeLater').load(function () {
$('#loading').hide();
$('#divShowMeLater').show();
});
})
Assume divShowMeLater is the div that contains all the content being loaded. The markup would look similiar to this:
<div id="divShowMeLater" style="margin-left:auto;margin-right:auto;text-align:center;" >
<div id="loading">Page loading...
<img src="images/ajax-loader.gif" alt="loading page..." />
</div>
</div>