Is it possible to search the contents of html files from another html page all within the same local directory? - javascript

So if given an offline webapp made up of html5/css/js with standard directories of {[Main Folder] > 0001.html, 0002.html, 0003.html, {[assets folder] > [css],[js],[media]}} is it possible for a search function on 1.html to be able to search the text content of 2.html or 3.html?
I haven't been able to find any specific information about this as most searching people do for a site are for sites intended to be houses on server, but in the case of an offline webapp the files are stored locally which causes a big hangup as webapi REALLY doesnt like a webpage looking at local files, but any images and links are able to be references through the href tag, so is it possible to search the contents of an html file specified through an href?
if given sample html pages:
0001.html
<!DOCTYPE html>
<body>
<div class="allSearch">
<div class="search">
<input type="text" id="searchInput" class="searchField"><button id="clear" class="clear">Clear</button>
<button type="button" id="button" class="searchButton">Search</button>
</div>
<div id="searchResults" class="results"></div>
</div>
</body>
0002.html
<!DOCTYPE html>
<body>
<div id="content">
<p>lorem ipsum</p>
</div>
</body>
Is it possible to search the contents of 0002.html while on 0001.html?
The reason i didn't include more robust markup and js above is that we are working on proprietary html ebooks built in InDesign and exported to html5. our current method of searching involves using a script in InDesign that parses every text box on every page and generates a dictionary that looks something like:
var searchDictionary = {
"Turtle": [1, 2],
"Fish": [2, 3],
"Fox": [3, 4],
"Snake": [4, 5],
"Dragon": [1, 5]
}
Where the content in "" is a term and the associated array are the page numbers that terms appears on, then you search that dictionary with the following js and return the page numbers that term appears on, which i coded up to pull in a pre-existing thumbnail and create a link to click through to the page:
document.getElementById("button").addEventListener("click", function () {
var query = document.getElementById("searchInput").value.toLowerCase();
var pages = searchDictionary[query];
if (pages === undefined) {
document.getElementById('searchResults').innerHTML = '<p style = \"text-align:center;width:100%\"> Term Not Found </p>';
}
else {
html = ""
html += '<ul>';
pages.forEach(showResults);
html += '</ul>';
}
}, false);
function gotopage(destinationpageNumber) {
var currentpagenumber = $('.page').attr('data-name');
currentpagenumber = parseInt(currentpagenumber);
destinationpageNumber = parseInt(destinationpageNumber.split(' ')[1]);
var distance = destinationpageNumber - currentpagenumber;
var offset = currentpagenumber - nav.current;
nav.to(nav.current+distance);
}
function showResults(value) {
var pageNum = value.toString();
var thumbMid = pageNum.padStart(4,0);
var thumb = '<img src=\"assets/images/pagethumb_' + thumbMid + '_0.jpg\" class=\"searchThumb\">';
var result = "<button id=\"goto\" + class=\"gotopagebutton\">pg. "+ value + "</br>" + thumb + "</button>";
html += '<li class=\"result\">' + result + '</li>';
document.getElementById('searchResults').innerHTML = html;
var gotopagebuttons = document.getElementsByClassName('gotopagebutton');
for (var i = 0; i < gotopagebuttons.length; i++) {
gotopagebuttons[i].addEventListener('click', gotopage.bind(null, gotopagebuttons[i].innerHTML));
};
}

You can make another file that could get the data from each of the files and attempt to filter it (https://www.w3schools.com/howto/howto_js_filter_lists.asp)

You can use fetch to open the file then use .text instead of .json. Then just search that text.
<script>
fetch('0002.html').then(function (response) {
return response.text();
}).then(function (html) {
console.log(html.includes("ipsum"))
}).catch(function (err) {
console.warn('Something went wrong.', err);
});
</script>

Related

How to create 'add to favourite' feature in a html cordova android app?

I am creating a song book app using phonegap. In index.html i have list of songs in li tags. when i click on a particular song it will open that particular song's lyrics in another local html file.
I want to add a 'favourite button'. When the favourite button is clicked I want that particular song to be added to the favourites list. When user open the favourite page it should display list of their favourite songs, and when they click a song in favourite page it should open that particular song's lyrics html page.
I am an intermediate user of HTML and a beginner in JavaScript.
Please help me accomplish this,
Thanks in advance.
Because this is a 'pretty broad' question, it is hard to find an answer for this, but I'd suggest making an array, storing the favorite songs into it, then when you open the favorites.html page, it gets the array, and writes the information to the page.
e.g. when a favorite button is clicked on a song page, it writes: the name of the song(exampleSong), the page of the song(exampleSong.html), and other random details that you need, and going to the favorites.html should get a document ready function that reads the array and writes the page.
Sorry if I can't help that much, but this was a really broad question.
If you need help, here are some examples that I created
(This gets the array of favorites, and prints them out)
var favorites = [
["ExampleSong", "exampleSong.html"],
["LorddirtCoolSong", "LorddirtCoolSong.html"],
["StackOverflowIsAwesome", "StackOverflowIsAwesome.html"]
];
var containerA = document.getElementById("favoritesA");
for (var i in favorites)
{
for (var j in favorites[i])
{
var newElement = document.createElement("p");
newElement.innerHTML = favorites[i][j];
containerA.appendChild(newElement);
}
}
var containerB = document.getElementById("favoritesB");
for (var i in favorites)
{
var newElement = document.createElement("p");
newElement.innerHTML = "<h4>Favorite Song " + i + "</h4>";
containerB.appendChild(newElement);
for (var j in favorites[i])
{
var newElement = document.createElement("p");
newElement.innerHTML = favorites[i][j];
containerB.appendChild(newElement);
}
}
var containerC = document.getElementById("favoritesC");
for (var i in favorites)
{
var newElement = document.createElement("p");
newElement.innerHTML = "<h4>Favorite Song " + i + "</h4>";
containerC.appendChild(newElement);
for (var j in favorites[i])
{
if(j == 1){
}else{
var newElement = document.createElement("p");
newElement.innerHTML = "<a href='" + favorites[i][1] + "'>" + favorites[i][j] + "</a>";
containerC.appendChild(newElement);
}
}
}
.favoriteSongs{
border: 2px solid black;
display: block;
}
<!--
EXAMPLE 1A: Print out the Favorites
-->
<hr>
<h2>Example 1A: Print favorites out</h2>
<div id='favoritesA' class='favorites'>
</div>
<hr>
<!--
EXAMPLE 1B: Now you know the order of the songs!
-->
<h2>Example 1B: Print favorites out with formatting</h2>
<div id='favoritesB' class='favorites'>
</div>
<hr>
<!--
EXAMPLE 1C: Link them
-->
<h2>Example 1C: Link to the page</h2>
<div id='favoritesC' class='favorites'>
</div>
<hr>
Very self explanatory, it gets the array of favorite songs, with the name and url, gets the container, which is <div id='favorites'></div> and writes the contents into it.
(oh wait, i just noticed I spent so long working on this hahaha.)
Examples:
1A: All I did was search the array favorites, and print out every single thing in the array. Simple.
1B: Slightly different, it's the same as the last, but I added a <h4> tag before every array in the array. (Yes, arrays inside arrays inside arrays are confusing).
1C: Instead of printing out both of the arrays inside the arrays, just print out the first thing inside the arrays in the arrays, and add a link pointing to the second thing inside the arrays in the arrays. Confused already? Just read it through and you'll understand.
Hi I found a solution using another SO question.
First we will create a local storage and store song details in that local storage key.
then we will retrieve that information in favorite.html using localStorage.getItem(key);
The following is my code for first song song1.html
when button pressed song link will be appended to local storage
<!DOCTYPE html>
<html>
<body onload="mySong()">
<button onclick="mySongOne()">add to favorite</button>
<script>
function mySong() {
localStorage.setItem("favsong", "");
}
function appendToStorage(name, data){
var old = localStorage.getItem(name);
if(old === null) old = "";
localStorage.setItem(name, old + data);
}
function mySongOne() {
appendToStorage("favsong", "<a href='https://www.song1.com'><h1>song1</h1></a>");
}
</script>
</body>
</html>
for another song song2.html
when button pressed second song link will be appended to local storage
<!DOCTYPE html>
<html>
<body>
<button onclick="mySongTwo()">add to favorite</button>
<script>
function appendToStorage(name, data){
var old = localStorage.getItem(name);
if(old === null) old = "";
localStorage.setItem(name, old + data);
}
function mySongTwo() {
appendToStorage("favsong", "<a href='https://song2.com'><h1>song2</h1></a>");
}
</script>
</body>
</html>
and favorite.html
on page load it will show details from local storage
<!DOCTYPE html>
<html>
<body onload="yourFunction()">
<div id="result"></div>
<script>
function yourFunction() {
document.getElementById("result").innerHTML = localStorage.getItem("favsong");
}
</script>
</body>
</html>

Using ReactJS to create print page

There has got to be a less brute force way of making a print page then the way I have been doing it. (See below code). Maybe with ReactJS and DOM insertions in some manner since the rest of my website is written with ReactJS? (See second example below) I have tried using the CSS #media print, but it does not work well on very complex websites in all the browser flavors. More recently, I have been making an entirely separate ReactJS website just for the print page and then passing it query strings for some of the information required on the print page. What a mess that makes!
var html: string = '<!DOCTYPE html>';
html += '<html lang="en">';
html += '<head>';
html += '<meta charset="utf-8">';
html += '<title>Title</title>';
html += '</head>';
html += '<body style="background-color: white;">';
html += '<div">';
html += getContent();
html += '</div>';
html += '</body>';
html += '</html>';
var newWin = window.open();
newWin.document.write(html);
newWin.document.close();
Second example:
var sNew = document.createElement("script");
sNew.async = true;
sNew.src = "Bundle.js?ver=" + Date.now();
var s0 = document.getElementsByTagName('script')[0];
s0.parentNode.insertBefore(sNew, s0);
Yeah there is, checkout react-print.
var React = require('react');
var ReactDOM = require('react-dom');
var PrintTemplate = require ('react-print');
class MyTemplate extends React.Component {
render() {
return (
<PrintTemplate>
<div>
<h3>All markup for showing on print</h3>
<p>Write all of your "HTML" (really JSX) that you want to show
on print, in here</p>
<p>If you need to show different data, you could grab that data
via AJAX on componentWill/DidMount or pass it in as props</p>
<p>The CSS will hide the original content and show what is in your
Print Template.</p>
</div>
</PrintTemplate>
)
}
}
ReactDOM.render(<MyTemplate/>, document.getElementById('print-mount'));

Another way to display JS on PHP page?

i am retrieving some information from Google's API and placing them in a single variable, and then inserting them to a div in the DOM like so:
$(function() {
// Load the info via Google's API
$.getJSON("https://www.googleapis.com/plus/v1/people/103039534797695934641/activities/public?maxResults=5&key=AIzaSyBaDZGM-uXuHc-VZZ2DINzVBcIDMN_54zg", function(data) {
// Variable to hold the HTML we'll generate
var html = '';
// how many posts we're displaying on the page
var numberOfPosts = 3;
// Loop over the results, generating the HTML for each <li> item
for (var i=0; i<numberOfPosts; i++) {
html += '<article>';
html += '<img src="'+data.items[i].actor.image.url+'">';
html += '<p>'+data.items[i].title+'</p>';
html += '<p>'+data.items[i].published+'</p>';
html += '</article>';
}
// Insert the generated HTML to the DOM
$('.google-posts-container').html(html);
});
});
My question is: is there a way to store every piece of information in each of its own variable, and then get the information individually by echoing the variable? So i dont have to hardcode all that HTML.
back in the days I would do:
<div id="google-posts-container">
<article>
<img src="{{image}}">
<p>{{title}}</p>
<p>{{published}}</p>
</article>
</div>
<script type="text/javascript">
// render a template (replace variables and return html)
function renderTemplate(tmpl, data){
for (k in data){
while(tmpl.indexOf('{{'+k+'}}') > -1){
tmpl = tmpl.replace('{{'+k+'}}', data[k]);
}
}
return tmpl;
}
$(function(){
// our template
var template = $('#google-posts-container').html();
$('#google-posts-container').html(''); // or clear()
$.getJSON("https://www.googleapis.com/plus/v1/people/103039534797695934641"
+"/activities/public"
+"?maxResults=5&key=AIzaSyBaDZGM-uXuHc-VZZ2DINzVBcIDMN_54zg", function(data) {
// Variable to hold the HTML we'll generate
var html = '';
// how many posts we're displaying on the page
var numberOfPosts = 3;
// Loop over the results, generating the HTML for each <li> item
for (var i=0; i<numberOfPosts; i++) {
html += renderTemplate(template, {
image : data.items[i].actor.image.url,
title : data.items[i].title,
publish : data.items[i].published
});
}
// Insert the generated HTML to the DOM
$('.google-posts-container').html(html);
});
});
</script>
nowadays I use angularjs
About comment by 'galchen' - don't use angular.js for serious &(or) big projects. Just look at source code.
(can't add sub comment, thats why i wrote to main branch)

How do I import, edit, and replace text in a txt file?

Using a client side script in a webpage (no server code), like javascript, how do I import, edit, and replace text in a txt file? I am simply trying to use two variables (Name and IP Address) and replace them in a text file. The existing text file is very long and I would like to automate this process. It would be nice for the script to also automatically create a new text file each time it is submitted. THANKS!
Here's my code:
<html>
<head>
<title>TExt File Changer v1</title>
<script type="text/javascript">
function findaNamendReplaceAll() {
var findaName = "Site_Name";
var findaCIP = "192.168.0.5";
var replaceaName = document.myInput.replaceWithName.value;
var replaceaCIP = document.myInput.replaceWithCIP.value;
var fulltexta = document.myInput.fulltext.value;
/*
var nr = new RegExp(findaName,"ig");
var tmp = fulltexta.replace(/Site_Name/gi, replaceaName).replace(/192.168.0.5 /gi,replaceaCIP);
document.myInput.fulltext.value = tmp;
*/
document.myInput.fulltext.value = fulltexta.replace(/Site_Name/gi, replaceaName).replace(/192.168.0.5/gi,replaceaCIP);
}
var str += ‘SECTION ethernet’/n;
str += ‘ETHERNET=UP’/n;
str += ‘BOOTP=server’/n;
str += ‘HOSTNAME=Site_Name’/n;
str += ‘IPADDR=192.168.0.4’/n;
str += ‘NETMASK=255.255.255.0’/n;
str += ‘DNS=‘/n;
str += ‘DHCP_RANGE_L=192.168.0.20’/n;
str += ‘DHCP_RANGE_U=192.168.0.100’/n;
str += ‘SEARCH=‘/n;
str += ‘ZEROCONF=YES’/n;
str += ‘ETH0_ADD_DEFAULT=on’/n;
str += ‘ENDSECTION ethernet’/n;
str += ‘‘;
</script>
</head>
<body>
<form name="myInput" onsubmit="return false">
<h1>Configuration Tool</h1>
New Site Name: <input type="text" id="replaceWithName" name="replaceWithName" value="">
<br><br>
New Camera IP: <input type="text" id="replaceWithCIP" name="replaceWithCIP" value="">
<br><br>
<button onclick="findaNamendReplaceAll()">Go</button>
<br><br>
<textarea id="fulltext" name="fulltext" rows="20" cols="100">
SECTION ethernet
ETHERNET=UP
BOOTP=no
HOSTNAME=Site_Name
IPADDR=192.168.0.4
NETMASK=255.255.255.0
DNS=
DHCP_RANGE_L=
DHCP_RANGE_U=
SEARCH=
ZEROCONF=YES
ETH0_ADD_DEFAULT=on
ENDSECTION ethernet
</textarea>
<br>
<button onclick="document.getElementById('fulltext').value = ''">Clear</button>
<button onclick="document.getElementById('fulltext').value = str">Restore</button>
</form>
</body>
</html></pre>
You can do it easily, provided you adhere to two limitations.
1) Internet Explorer on windows
2) Use of ActiveXObjects
I did a project that required assembling various data as found in excel spreadsheets. My input file was a hand-edited json file - specifying things like filenames and paths. Once the json was loaded, I used an ActiveXObject to open and control Excel in just the same manner as one would from within a VBA program.
As a result, I don't have any code to load arbitrary data from an arbitrary filename.
However, this snippet should give you enough to get started.
Note: The code assumes that IE still gives you a fully qualified path for any file selected with an <input type='file'/> Chrome, FF and Opera only give you the filename - they do not tell you which folder it resides in.
function byId(e){return document.getElementById(e);}
function writeDataToFile()
{
var mFSO = new ActiveXObject("Scripting.FileSystemObject");
var mFile = mFSO.createtextfile(outputFilename);
mFile.write( byId('outputTextArea').value );
mFile.close();
alert("text saved to '" + outputFilename + "'");
}

Unable to retrieve values from eBay API response using Javascript

I am trying to build a very simple tool for use at my work. I work for eBay and currently the tools available are cumbersome for the task. We are asked to compare text and images to check that sellers aren't stealing each others content. I am using the eBay Trading API and the sample HTML/CSS/Javascript code given when the developer account was created. Ultimately what I hope to achieve is a simple page that displays two items' photo and description next to each other. However, right now I am simply trying to edit the sample code given to display the start date of the auction.
My question is this: I am trying add a variable who's value is determined by a response from the API. some of these are provided in the sample however, when I add my own var starttime = items.listingInfo.startTime to the function and add the variable to the HTML table none of the data displays including those that displayed prior to my addition. Unfortunately I don't have more than a rudimentary understanding of javascript and so am unsure if I am even properly phrasing this question, let alone getting the syntax of my addition correct. What am I doing wrong?
below is the sample text with my addition of one declared variable (starttime) and one addition to the HTML table
<html>
<head>
<title>eBay Search Results</title>
<style type="text/css">body { font-family: arial,sans-serif;} </style>
</head>
<body>
<h1>eBay Search Results</h1>
<div id="results"></div>
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var viewitem = item.viewItemURL;
var starttime = items.listingInfo.startTime;
if (null != title && null != viewitem)
{
html.push('<tr><td>' + '<img src="' + pic + '" border="0">' + '</td>' +
'<td>' + title + '' + starttime + '</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=iphone%203g&paginationInput.entriesPerPage=3>
</script>
</body>
</html>"
If you believe listingInfo is an property of individual items, and that it is an object that has the property startTime, then the proper syntax is:
var item = items[i];
var title = item.title;
var viewitem = item.viewItemURL;
var starttime = item.listingInfo.startTime;
You are currently referencing items which is the array of items, not an individual item.
Update
I looked into this via the URL you put in the comments. The solution to this particular problem is this:
var starttime = item.listingInfo[0].startTime;
I hope that helps. Please review the FAQ; Imho this question falls outside the scope of this site (the question is really quite narrow, and not likely to help anyone else). I recommend Mozilla Developer Network as a source for learning more about JavaScript.

Categories