Navigation between pages - html - javascript

I trying to navigate between 3 pages which contain the same header and footer but each page has different content.
I want to load different contents html on hash change.
The problem is that when I click on the same page again, the content.html loaded again.
How can I use the content without loading the html again and again, using java script/html/jquery?
Code example:
Navigationbar.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Navigation Bar</title>
<link rel="stylesheet" type="text/css" href="css/navigationbar.css">
</head>
<body>
<nav>
<img id="navigation-bar-logo" class="logo" src='images/flybryceLogo.png'>
<ul class="navigation-bar-ul">
<li class="navigation-bar-li"><a id="navigation-bar-contact-page-tab" href="#contact.html">CONTACT</a></li>
<li class="navigation-bar-li"><a id="navigation-bar-about-us-page-tab" href="#aboutus.html">ABOUT US</a></li>
<li class="navigation-bar-li"><a id="navigation-bar-home-page-tab" href="#home.html">HOME</a></li>
</ul>
</nav>
</body>
</html>
initial.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>One Page Test</title>
<link rel="stylesheet" type="text/css" href="css/homepage.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div id="main-container" class="main-container">
<div id="header" class="header">
</div>
<div id="content" class="content"></div>
<div id="footer" class="bot"></div>
</div>
<script>
document.onreadystatechange = function(){
if (document.readyState == 'complete') {
window.onhashchange=hash_change;
window.onload=hash_change;
if(window.location.hash==''){
//default hash
window.location.replace('#home.html');
}
//load the header
$("#header").load("fragments/navigationbar.html");
//load the footer
$("#footer").load("fragments/footer.html");
}
}
function hash_change()
{
//get the new hash
var newHashCode = window.location.hash.substring(1);
if (newHashCode === "home.html"){
$("#content").load("home.html");
} else if (newHashCode === "aboutus.html") {
$("#content").load("aboutus.html");
} else if (newHashCode === "contact.html"){
$("#content").load("contact.html");
}
}
</script>
</body>
</html>

A longer but suitable solution would be to build a content cache on your own.
For example asking to the server just once the html and then setting it to the $('#content') element. You can use this helper function.
var contentsCache = {};
var getAndCache = function(url, callback) {
var cachedContents = contentsCache[url];
if (!cachedContents) {
$.get(url, function(serverContents) {
cachedContents = serverContents;
contentsCache[url] = cachedContents;
callback(cachedContents);
});
} else {
callback(cachedContents);
}
};
And then replace the $('#content').load calls by calls to this new asynchronous way.
function hash_change()
{
var fillContentCb = function(s) {
$('#content').html(s);
};
//get the new hash
var newHashCode = window.location.hash.substring(1);
if (newHashCode === "home.html"){
getAndCache("home.html", fillContentCb);
} else if (newHashCode === "aboutus.html") {
getAndCache("aboutus.html", fillContentCb);
} else if (newHashCode === "contact.html"){
getAndCache("content.html", fillContentCb);
}
}
As suggested in some comments, consider using native HTML navigation instead. Another suggestion is to use a client-side JS framework which supports routing if this application is likely to grow.

Add an if condition that checks whether the current hash location matches with the one that's been clicked on, and if it does just return. You'd have to store it in a global JS variable, and set it every time you navigate.

Related

Automatically refreshing a page at set interval using AJAX and JQuery

I am trying to refresh a page at a interval of 5 seconds which should update the view with latest data from the SQL Server. Below is the code.
#model Test.Data.Domain.ManufacturingCdMachine
#{
ViewBag.Title = "Rimage Details";
ViewBag.JobId = Model.CurrentManufacturingJobId;
}
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" id="navbar">
<div class="container">
<div class="navbar-header">
</div>
</div>
</div>
<div id="CdMachineDetails">
#if (#Model.CurrentManufacturingJobId != null)
{
<div>
#{Html.RenderPartial("_CdMachineJob");}
</div>
}
else
{
<div>
#{Html.RenderPartial("_MachineInIdle");}
</div>
}
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
</body>
</html>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor(Math.random() * 100);
$.ajax({
type: "GET",
url: "/Mobile/CdMachine/Details/" + #Model.ManufacturingCdMachineId,
data: {
},
success: function (result) {
//Sets your content into your div
$('#CdMachineDetails').html(result);
}
});
}, 5000);
});
</script>
The URL of my page is http://localhost:28886/Mobile/CdMachine/Details/1
However the page not seem to be refreshing. What am I doing wrong?
-Alan-
you have syntax error in your JS. I think you are missing bracket at the end of your JS code.
Ajax doesn't refresh page - you just get content which you can of course place on the DOM or can manipulate it as you wish.
URL pointing to your localhost server will not work of course - must be placed public.

scribd set page not working

I am using scribd to display pdf. By clicking on the Page 3,Middle,End links the corresponding pages should load. But the pages are not loading properly. And in FF i am not getting any errors. But in chrome console i am getting this error. Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://www.scribd.com') does not match the recipient window's origin ('https://www.scribd.com'). Can anyone help me out in this?
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Scribd Javascript API Demo</title>
<script type="text/javascript" src='https://www.scribd.com/javascripts/scribd_api.js'></script>
</head>
<body>
<div id="container">
<div id='col1'>
<div id='embedded_doc'><a href='https://www.scribd.com'>Scribd</a></div>
</div>
<div id='col2'>
<h2 id="header"> Loading Document... </h2><br/>
<span id="author"></span>
<div id="bookmarks">
<h4>Bookmarks</h4>
<ul>
<li>Page 3</li>
<li>Middle</li>
<li>End</li>
</ul>
</div>
<div id="comment"></div>
</div>
<div class="clearfix"> </div>
</div>
<script type="text/javascript">
// Data
// Instantiate iPaper
var scribd_doc = scribd.Document.getDoc(2520449, 'key-1127428tb3rbejns9bhr');
// Parameters
scribd_doc.addParam('height', 420);
scribd_doc.addParam('width', 530);
scribd_doc.addParam('auto_size', true);
scribd_doc.addParam('mode', 'slideshow');
scribd_doc.addParam('jsapi_version', 2);
// Write the instance
scribd_doc.write('embedded_doc');
// Bookmark Helpers
var goToPage = function(page) { alert(scribd_doc.api.getPageCount());
if (scribd_doc.api){
scribd_doc.api.setPage(3);
}
}
var goToMiddle = function() {
if (scribd_doc.api){
goToPage( Math.floor(scribd_doc.api.getPageCount()/2) );
}
}
var goToEnd = function() {
if (scribd_doc.api) {
goToPage(scribd_doc.api.getPageCount());
}
}
</script>
View Source and you'll see that this is all dynamically generated using the Scribd Javascript API.
</body>
</html>
I fixed this issue by downloaded the scribd_api.js file and modified the path to https in js. And now the set page is working without any errors.

How to call a javascript function in an opened child window

I have a parent html file and want the user to click something which should then open a new window (or tab) containing the (dynamically generated) contents of a div in the parent (which is hidden in the parent).
From my reading here and elsewhere something like this should work:
parent.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Parent</title>
<script src="/js/jquery-1.11.0.min.js"></script>
</head>
<body>
<div id="from">
html from parent
</div>
<div id="launcher">
launch child
</div>
<script type="text/javascript">
$("#launcher").click(function() {
var child = window.open('child.html', '_blank', '', false);
if (child) {
var html = $("#from").html();
//window.setTimeout(child.addHTML(html), 5000);
child.addHTML(html);
}
else {
alert('Please allow popups for this site');
}
});
</script>
</body>
</html>
child.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Child</title>
<script src="/js/jquery-1.11.0.min.js"></script>
</head>
<body>
<div id="to"></div>
<script type="text/javascript">
function addHTML(html) {
$('#to').html(html);
}
</script>
</body>
</html>
However, regardless of using the commented-out setTimeout (incase the child hadn't loaded yet before calling the child's function), I get this error (in Safari, similar in Chrome) immediately:
'undefined' in not a function (evaluating 'child.addHTML(html)')
What am I doing wrong? Is there a better way to achieve my goals?
The first parameter of window.setTimeout should be the function to execute.
Try this:
if (child) {
var html = $("#from").html();
window.setTimeout(function(){child.addHTML(html);}, 5000);
}
I built a small example::
http://jsfiddle.net/rt19hv7v/
if the goal is only to add the content and not to call a function u can do it this way
if (child) {
child.addEventListener('load', function () {
var html = $("#from").html();
$('#to',child.document).html(html)
});
}else {
alert('Please allow popups for this site');
}

unable to bind image to img tag

I am practicing Windows Phone development using WinJS and I have the following code which parses JSON received from a particular URL. And using the images to be bound to a list view in an HTML page,
JavaScript code:
WinJS.xhr({ url: urlToBeUsed }).then(
function (sportsResponse) {
var sportsJSON = JSON.parse(sportsResponse.responseText);
var listItems = sportsJSON.Videos.Data;
for (var i = 0; i < listItems.length; i++) {
var imageList = listItems[i].Items;
var count = imageList.length;
if (count > 0) {
listItems[i].Items[0].Images.forEach(imageIteration);
function imageIteration(value, index, array) {
var picture = value.Url;
var name = value.title;
sportsImageList.push({
title: name,
picture: picture
});
}
}
}
imageList.itemDataSource = sportsImageList.dataSource;
})
}
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- WinJS references -->
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<script src="/js/navigator.js"></script>
<link href="/css/default.css" rel="stylesheet" />
<link href="/pages/home/home.css" rel="stylesheet" />
<script src="/pages/sports/sports.js"></script>
</head>
<body>
<!-- The content that will be loaded and displayed. -->
<div class="fragment homepage" style="width:100%;height:100%;padding:10px">
<div class="myTemplate" data-win-control="WinJS.Binding.Template">
<div class="myItem">
<img data-win-bind="src:picture" style="width:100px;height:100px" />
</div>
</div>
<div id="imageList" data-win-control="WinJS.UI.ListView" data-win-bind="winControl.itemDataSource:sportsImageList.dataSource" data-win-options="{itemTemplate:select('.myTemplate')}"></div>
</div>
</body>
</html>
I have tried many ways to bind the URL to the Image, but on the screen I can only see the links but not the actual images.
Where am I wrong?
All help and suggestions appreciated.
Thank you!
I believe your error is in your assignment line, remember that itemDataSource is a property of the ListView control. As it is in your code you're assigning that property to the imageList element.
Change it to this:
imageList.winControl.itemDataSource = sportsImageList.dataSource;

how to run a callback function after $.mobile.changePage is ready in jquery?

in this project im using jquery and phonegap
i have a link that if clicked , changes the page:
$('#statsButtonmain').on('click', function() {
$.mobile.changePage("stats.html", { transition: "slideup"}, true, true);
});
this works fine, but i would like to run a function (playMusic()) when the transition is done, something like this:
$('#statsButtonmain').on('click', function() {
$.mobile.changePage("stats.html", { transition: "slideup"}, true, true);
playMusic();
});
i found out that there is a pageshow event that gets triggered on the page being shown, after its transition completes, but im not sure how to use it
this doesn't seem to work, any ideas?
Thanks
I've not done a lot a jQuery mobile development so this might not be the most efficient solution. As you said, the pageshow event is what you need to use. Here are the 2 HTML files I ran locally in which I see the alert after the stats.html page transition is completed. The .live() is bound to the #stats element's page pageshow event.
HTML
(saved as index.html)
<!doctype html>
<html>
<head>
<title>Home</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#statsButtonmain').on('click', function() {
$.mobile.changePage('stats.html', { transition: 'slideup'}, true, true);
});
$('#stats').live('pageshow', function(event, ui) {
playMusic();
});
function playMusic() {
alert('playing music');
}
});
</script>
</head>
<body>
<div data-role="page" id="home">
<div data-role="header">
<h1>Callback test</h1>
</div>
<div data-role="content">
click me
</div>
</div>
</body>
</html>
(saved as stats.html)
<!doctype html>
<html>
<head>
<title>Stats</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.js"></script>
</head>
<body>
<div data-role="page" id="stats">
<div data-role="content">some stats</div>
</div>
</body>
</html>
I hope this helps someone. It also retains the query string between pages too.
async function loadPage(_url) {
let promise = new Promise((resolve) => {
var _query = "";
if (window.location.href.includes("?")) {
if (window.location.href.split("?").length >= 2) {
_query = "?" + window.location.href.split("?")[1];
}
}
$.mobile.changePage(_url + _query);
var currentPage;
function checkCurrentPage() {
if (typeof $("body").pagecontainer != "undefined") {
currentPage = $("body").pagecontainer("getActivePage");
if (currentPage[0].baseURI.includes(_url)) {
clearInterval(loadPageInt);
resolve();
}
}
}
var loadPageInt = setInterval(function () {
checkCurrentPage();
}, 100);
});
return await promise;
}
Usage:
loadPage('file.html')
.then(() => {
// do some stuff now the page has changed to file.html
});

Categories

Resources