I've been searching for an answer to this and can't seem to find out how to do it...or if it is possible.
I have a JavaScript Program that displays an .HTML page. I have an API from another company that sends us information as well. I would like to be able to change the contents of the .HTML page before the user sees it. Is this possible?
For example, suppose page.html is:
<HTML>
<HEADER>
<TITLE>
The Company Name
</TITLE>
</HEADER>
<BODY>
Some stuff
</BODY>
</<HTML>
page.html is housed on our server and using JavaScript/HTML I would like to change the value of "The Company Name" with the value from the API before the page is rendered to the user. Is this possible?
window.onload would not do the trick if you want to be sure that your users don't see the page before edition, as onload waits for everything to be loaded, including images.
What I recommend is :
to change the title in a block in the head : <script>document.title="test"</script>
to hide initially the page, by enclosing it in a <div id=wholepage style="display:none;">
to change the page content in a standard <script> block included at the end of your body
to render your big div visible at end, using document.getElementById('wholepage').style.display='block';
A simple Javascript function will do the trick:
window.onload = function() { document.getElementByTagNames("title")[0].value = "Yourvalue"; }
You could load the HTML from the page into a string variable. Then you'd use regex on the string and search for the starting expression and ending expression , and do a replace on that content. Javascript has a replace method.
var str="<HTML><HEADER><TITLE>The Company Name</TITLE></HEADER><BODY>Some stuff</BODY></<HTML>";
str=str.replace("<TITLE>","<DUMMY>");
str=str.replace("</TITLE>","</DUMMY><TITLE>your real title</TITLE>");
Essentially you would rename the title tag into a non existent tag like dummy, then append the real title tag to the end of it.
Then you can display the HTML content in the string/variable in a page at runtime.
Related
I have multilingual single page html application where I set html of tags by calling function on document.ready. However I am not getting html of any tag in page source when I view page on View Page Source. How can I get the tags in page source? document.ready is in the last script tag of the page.
$(document).ready(function() {
var lang = // get the language.
translateFunction(lang);
});
Below function is in js file. This file is added above the last script tag (i.e. document.ready script).
function translateFunction(lang) {
$("[tkey]").each(function (index)
{
var strTr = lang_resource[lang][$(this).attr('tkey')];
$(this).html(strTr);
});
}
<h1 tkey="firstH1"></h1>
Language wise data is in json format in the same js file with translate function.
When I view the page source, I see only
<h1 tkey="firstH1"></h1>
Where it needs to be like below,
<h1 tkey="firstH1">Anything from the translate function.</h1>
On the page, you can see the desired output, but in the page source, I am not getting html set. What I want to do is, I want set html of the tags in javascript on document.ready. How to do it?
EDIT
We want to add meta tags. And set keywords and description language wise. This is the main concern. The keywords and description are set in translate function. Will the crawler take the keywords and description?
We have two links language wise in site map. So when user select say french language, it will redirect to www.mysite.com?lang=fr and all the tags are set in french language. So the meta keywords and description.
Firstly if this is the exact code,
$(document).ready(function() {
var lang = // get the language.
translateFunction(lang);
});
there is error in itself...
there should be some value for var lang
I am using angularjs for part of my page say single component, which is used in many pages.Now my problem is hash url does not work now.
Example: I have a div#hello in my page and URL is given as Url#hello.but it does not go to that particular div just the top of the page is diaplayed.
So could you guys help me here please?
NOTE:The url#hello is changing to url/#hello.The page cannot be changed to angular and only that single component use angular.
EDIT: Thank you Stephen:) yes, of course, we need to use routing.The thing is, after page load, if we change the url back to URL#hello it works.So is it possible to do it in other way apart from Routing and $angularscroll ?(i.e) just from the JS or jQuery perspective ?
Ok, thanks. I've misunderstood you. I think I have a better understanding now. Please correct me if I am wrong:
So, you're essentially trying to make a hello link that points to a section within the same page. When you change the url to pageUrl#hello the page should jump down to the section with the id called hello.
But the problem is that since your section has an AngularJS component that uses the ngRoute module, this routing functionality is making your page redirect to pageUrl/#hello instead of jumping to the HTML section with the id='hello'.
Is this correct?
Solution
If I understand your problem correctly, the solution is to check if your ng-app='appName' attribute is on the body tag. If it is, then move it down to your component's parent element.
If a hash link is a child of the ng-app element, then when you click it AngularJS thinks you want to redirect to another view. This is what causes the Home link to redirect to pageUrl#/home.
<body ng-app="demoApp">
Hello <!-- redirects to #/hello -->
<div id="hello"></div>
<!-- ... -->
So if you put the hash link outside of the ng-app element then it will behave as expected when you click it.
<body>
Hello <!-- jumps to the 'hello' div -->
<div id="hello" ng-app="demoApp"></div>
<!-- ... -->
On Page Load
If you want the page to jump to the hello div on page load, then set window.location = '#hello' inside your controller. Then, when you visit pageUrl#hello, the hello div should appear instead of the top of the page.
If you don't have a controller, or don't want to use one, then after your document loads, check the hash url and change it programmatically.
$(document).ready(function(){
if(window.location.hash == '#hello'){
window.location = '#hello';
}
})
I'm looking to solve the issue of not being able to Save/Apply changes to an .html document when the document.createElement("div"); is used in JavaScript. I want to be able to save the changes made to the document and 'overwrite' the original .html document.
Future Possibilities(these can be ignored):
Deletion of these elements, and saving those changes as well to revert it back to it's original state.
EDIT: --------------
I didn't make this clear, sorry!
THIS CODE IS TO EMBED MULTIPLE YOUTUBE VIDEOS ON A SINGLE PAGE; I WOULD LIKE SOME HELP HAVING SOMETHING OVERWRITE THE ORIGINAL .HTML DOCUMENT. THEREFORE LOADING THIS NEW CONTENT EACH TIME SOMEONE OPENS THE PAGE.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="container">
<div id="header" align="center">Home</div>
<div align="center">
<button onclick="myFunction()">Button</button>
</div>
<div id="parentElement" align="center">
</div>
<script>
function myFunction() {
var parentElement = document.getElementById('parentElement');
var theFirstChild = parentElement.firstChild;
var newElement = document.createElement("div");
parentElement.insertBefore(newElement, theFirstChild);
newElement.setAttribute("id", "newElement");
var embed = prompt("Please enter your YouTube Embed Link");
if (embed != null) {
document.getElementById("newElement").innerHTML = embed;
}
}
</script>
</body>
</html>
I think what you're asking is how to put dynamic content in a static web page. This is not my area of expertise, but I can give you the outlines of how to do what you're trying to do. This is the architecture. You'll have to fill in some implementation details yourself, but I'll try to give you a clear idea of what you'll be googling for at each step of the way.
Suggestions for improvement from real web guys will be eagerly embraced. If there's already an answer on SO that walks a noob through the design of a trivial single-page AJAX/JSON web app, I can't find it. There must be one, though.
This is a lot more complicated than your original idea, but rewriting a web page not a great idea: You're writing arbitrary zeroes and ones from strangers to a file on your server. You need one HTML file per user, if you store their data in HTML files. How do you serve him the right one? What if you change the layout after you have 500 users? You'd be writing a script to alter the text of 500 HTML files. In practice it's just a horrorshow.
What you're groping for is dynamic content via AJAJ, which we usually still call AJAX for historical reasons (prior to the advent of CNC machining, curly braces were difficult to mass produce economically, and so web services commonly used pointy brackets instead).
First, write a web page to serve the user's personal content. It'll save updates as well. May as well use PHP. That "page" isn't a web page; instead of HTML, it returns JSON text with a content-type of application/json. The user can POST text to it in JSON format as well. This "page" is a web service.
On a get request, the web service page, given a username (and appropriate security), will retrieve the user's YouTube video list from MySQL and return it to the caller as JSON.
For now, the content going to and from that web service page is pretty simple. Just a list of URLs. Let's make it an object that has one member, and that one member will be an array of objects that contain information about YouTube videos the user has chosen. For now, each one just has a URL, but we may want to add more detail later, so we won't just make it an array of bare URL strings. At the top level, we'll also be able to add other types of content alongside "YouTubeVideos" if there's a need -- for example, you're going to want a username and a security token.
{
"YouTubeVideos": [
{
"url": "http://youtu.be/LKJDFKLJDF"
},
{
"url": "http://youtu.be/87sdfd234"
}
]
}
In the HTML page, your JS code will first request the user's data from that web service in onLoad. You'll do that using XMLHttpRequest. You'll use the JavaScript function JSON.parse to turn the response text into a JS object.
So write a function called requestUserYTContent or something, and call that from onLoad. This is simplified: There's no validation, exception handling, etc.
// Empty default instance to start out.
var ytInfo = { "YouTubeVideos" : [] };
function requestUserYTContent() {
// ...
// Do stuff with XMLHttpRequest to get the JSON for this user from
// the web service.
// ...
ytInfo = JSON.parse(http_request.responseText);
console.log('Got ' + ytInfo.YouTubeVideo.length + ' videos');
// Once you've got that JSON object, you can loop through the
// videos and do stuff with their urls. We'll stick that loop in
// another function so we can re-use it in cases where the list
// changes for reasons other than a web service call.
var ytDiv = document.getElementById('ytContent');
ytDiv.innerHTML =
generateVidListHTML(ytInfo.YouTubeVideos);
}
function generateVidListHTML(vids) {
var newHTML = '';
for (var i = 0; i < vids.length; ++i) {
var url = vids.YouTubeVideos[i].url;
// ...generate HTML to display this video, and append to
// newHTML
}
return newHTML;
}
So we keep that ytInfo around in a global variable. When the user adds to the list or deletes from it, alter the list, re-generate the HTML with generateVidListHTML(), insert the HTML into the page as above, and then post the newly-altered list as JSON back to the web server to update the user's content in the mySQL database.
You'll POST data back to the web service with XMLHttpRequest. Here's an example. You'd be using a different content-type, of course.
https://stackoverflow.com/a/9713078/424129
In JavaScript in the web page, converting a live JavaScript object back to JSON is easy: https://stackoverflow.com/a/4162803/424129
For simplicity, you may as well just pass the same JSON format back and forth.
When you send JSON back to the web service, it'll need to parse it too. I don't know how to parse JSON in PHP, but I know somebody who does:
https://www.google.com/search?q=how+to+parse+json+in+PHP
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="container">
<div id="header" align="center">Home</div>
<div align="center">
<button onclick="myFunction()">Button</button>
</div>
<div id="parentElement" align="center">
<div id="newElement" style="display: hidden"></div>
</div>
<script>
function myFunction() {
var embed = prompt("Please enter your YouTube Embed Link");
if (embed != null) {
document.getElementById("newElement").innerHTML = embed;
$('#newElement').css('display','inline');
}
}
</script>
</body>
</html>
just taking out the parent - child element relationship in javascript code and put the new element div in html with display:none style attribute. Then in click function, just make it visible.
Cheers!
It took sometime to understand your requirement infact still now it is not clear .But from your code I understand that you are trying to get a text from prompt message and initally you want to display it in your page.But that is not working since you are not able to execute it.
document.getElementById("newElement").innerHTML
Rather that using innerHTML you can check textContent.
Here is a minor change in your function
if (embed != null) {
newElement.textContent = embed;
}
WORKING COPY
I've got a website and I'd like to make a part of it static. What happens is that the header, the menu bar and the footer are consistent in every page. I'd like to have them always loaded and when I click the menu button, it will only reload what is the body of the site.
Is there a simple chunck of code that can early achieve this? Something in js or ajax? I'm sorry but I don't have enough experience in these languages to accomplish something on my own. I've already tried to check jQuery library but it's still pretty confusing to me.
Thank you.
I think you don't even need Ajax or css!! Just use iFrames!! They are awesome, what happens is that u only design one page as the holder of your static content (Header-Menu ...) and put one iFrame in there as a place holder for any page you want to load in it, u should use proper css code to place the iFrame where you want, now, for every link in your menu, just set the "target" attribute equal to your iFrame's name and all the links will be loaded in that iFrame and your page won't be reloaded with every link click... I'll be back with some code...
Just add in every page a div container with ID for header, menubar and footer and just load it with this:
$(document).ready(function(){
$('#header').load('header.html');
$('#menubar').load('menubar.html');
$('#footer').load('footer.html');
});
Just make sure that the html files don't have html, head or body tags within, only the HTML-Code you would write inside the div. It's just like the include function in PHP.
EDIT:
For easy and simple implementation store the code above inside a .js file (e.g. include.js) and add this inside every head just below the include of all other scripts of your html files:
<script type="text/javascript" src="include.js"></script>
EDIT2:
Another solution ist to load the content of the page instead of the header, menubar, footer.
Here you take the same specifications (no html, body, etc. tags inside your content html files)
Name your content div e.g. <div id="content"></div>
Your navbar for example:
<div id="navbar">
Content1
Content2
</div>
JavaScript Code:
$(document).ready(function() {
//Click on a link that's child of the navbar
$('#navbar > a').click(function() {
//Get the html file (e.g. content1.html)
var file = $(this).attr('href');
//Load this file into the #content
$('#content').load(file);
return false;
});
});
You should consider the use of Server Side Included : http://httpd.apache.org/docs/current/howto/ssi.html
It's not quite easy to understand (as it refer to apache configuration), but this is a really great solution.
In a nutshell, you include parts of html code in you main page :
<!--#include virtual="/footer.html" -->
You won't have to use or understand all JQuery Framewol, user agent won't have to parse (if they are able to !) Javascript.
This is a pretty good replacement of PHP / ASP / Java for this kind of purpose.
You could use ajax to request the body of each page. But this is only one possibility - there are many. An other approach could be to create you page content using a script language (php, perl) serverside and employ a function there which adds footer, header and anything else to each page.
If you have an idea of Jquery then use click event on menu links to load the page in a div like the following syntax may help you.
$(document).ready(function(){
$("a.menu").click(function(){
$("#bodyContent").load("http://abc.com/your-linked-page.html");
});
});
To load the url dynamically use the following code:
In your menu bar the link looks like:
Home
In your Jquery code:
$(document).ready(function(){
$("a.menu").click(function(){
url = $(this).attr("title"); // here url is just a variable
$("#bodyContent").load(url);
});
});
Step 1: Add Jquery file into your html page.
Step 2: Use the above jquery code and change your menu link to the new what i said here.
Step 3: If you done it correctly, It will work for you.
How about a traditional iframe?
In your menu:
<a target="body" href="URL_to_your_Menu1_page">Menu1</a>
and then further in the document:
<iframe name="body" src="URL_to_homepage"></iframe>
You may use frameset and frames and organize you pages accordingly. So, frames containing menus can always be at display and while displaying contents on click of menu u may set target to frame in which you would like to load the contents.
Is there any way to display the title of the Webpage in pure text(HTML, Javascript)? I am making a mobile website that involves displaying a lot of text and It would be easier if I just had the website write the title on the toolbar on its own.
With javascript you can access it via document.title
Example: http://jsfiddle.net/AlienWebguy/ZvmWL/
Not sure if I understand your problem correctly, but you may acces the title Element like any other Element in the Document:
var title = document.getElementsByTagName("title")[0] ;
There is also a shortcut to the title Node's text content (link) in the Document Object:
var text = document.title
The title Element is a required part of any HTML Document so replacing it -- if that is what you wanted to do -- is not legal (link).
if you are using HTML then you would use <title>. I have an example for you down below:
<html>
<head>
<title>What you want to name the webpage</title>
</head>
</html>