How to capture text in first line of current screen in Android? - javascript

My projec is a e-book reader application. There is only a VebView in screen and getting data from html file. It has only text content. I need to do get text in first line of current screen. In next step, I need to find the text in document and getting the text's position of screen. Finally, I need to scroll the found position. All of things necessary to solve that problem: (WebView Text Zoom Issue in Android)
html content:
<!DOCTYPE html>
<head>
<style type="text/css">
p{} p.x1{} p.x2{} p.x3{} p.x4{}
h2.x1{} h2.x2{} h2.x3{} h2.x4{}
</style>
</head>
<body>
//paragraph-1
<p class="x1">Title-1</p>
<p class="x2">Title-2</p>
<p class="x3">Title-3</p>
<p class="x4">Title-4</p>
<p>Text content.</p>
//paragraph-2
<h class="x1">Title-1</p>
<h class="x2">Title-2</p>
<p>Text content.</p>
//paragraph-3
<h class="x3">Title-1</p>
<h class="x4">Title-2</p>
<p class="x3">Title-3</p>
<p>Text content.</p>
//paragraph-4
<h class="x2">Title-1</p>
<p class="x3">Title-2</p>
<p>Text content.</p>
//...
</body>
</html>

I think you are searching for this?
function findTopObject (elements) {
var top = Number.POSITIVE_INFINITY;
var obj = null;
Array.from(elements).forEach(function (o) {
var t = o.getBoundingClientRect(o).top;
if (t > 0.0 && top > t) {
obj = o;
top = t;
}
});
return obj;
}
for (var i = 0; i < 1000; i++) {
var p = document.createElement("p");
p.innerText = "Line " + i;
document.body.appendChild(p);
}
var elements = document.querySelectorAll("p");
var obj = null;
window.onscroll = function() {
if (obj != null) {
obj.style.backgroundColor = "";
}
obj = findTopObject(elements);
if (obj != null) {
obj.style.backgroundColor = "red";
}
};
function findTopObject(elements) {
var top = Number.POSITIVE_INFINITY;
var obj = null;
Array.from(elements).forEach(function(o) {
var t = o.getBoundingClientRect(o).top;
if (t > 0.0 && top > t) {
obj = o;
top = t;
}
});
return obj;
}
<body></body>

There is no direct way to do what you want,
First get html content by doing
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
Then use sub string conccept to get what you want, have look Get Html content
Or you can use Jsoap parser
to get value from specified tag in HTML
Document doc=Jsoup.connect("http://www.yahoo.com").get();
Elements elements=doc.select("img");
for(Element e:elements)
{
System.out.println(e.attr("src"));
}

Related

Simple Typing game (JavaScript)

I am trying to create a typing game that allows users to input the correct alphabets for the word displayed on the screen. If any wrong alphabet is used as input the game won't show a new word until all the alphabets are correctly provided as input. What I am not able to figure out is how I do match multiple characters with Array elements. Here is my code sample.
var p = document.getElementById('word');
document.addEventListener('keyup', keyboardEventsHandle , false);
var wordsList = ['america','japan','italy','jordan','turkey'];
function keyboardEventsHandle(e){
p.append(e.key);
if(e.key=='a')
{
alert('You typed A');
}
}
<html>
<head>
<title>Simple Typing Tutor</title>
</head>
<body>
<p id="word"></p>
<h3> america </h3>
<script src="javas.js"></script>
</body>
</html>
var p = document.getElementById('word');
var word = document.getElementById("toType")
document.addEventListener('keyup', keyboardEventsHandle , false);
var wordsList = ['america','japan','italy','jordan','turkey'];
var gameRunning = true
var charIndex = 0;
var wordIndex = 0;
function keyboardEventsHandle(e){
// If you use append here. Every character gets printed out
// p.append(e.key);
if(e.key==wordsList[wordIndex].charAt(charIndex) && gameRunning)
{
// If you use append here only correct characters get printed out
p.append(e.key)
alert('Correct!');
if (wordsList[wordIndex].length == charIndex + 1) {
// Defines which word should get controlled
if (wordsList.length == wordIndex + 1) {
gameRunning = false;
alert('Done');
} else {
wordIndex++;
charIndex = 0;
word.innerHTML = wordsList[wordIndex];
p.innerHTML = "";
}
} else {
// Defines which character of the word should get controlled
charIndex++;
}
}
}
<html>
<head>
<title>Simple Typing Tutor</title>
</head>
<body>
<p id="word"></p>
<h3 id="toType"> america </h3>
<script src="javas.js"></script>
</body>
</html>
You can create a list of elements to match and then do something like this:
const wordsList = ['america','japan','italy','jordan','turkey'];
const listToMatch = ['america','japan'];
let trueOrFalse = listToMatch.every(i=> wordsList.includes(i));
console.log(trueOrFalse) //true
var anotherList = ['america', 'India'];
trueOrFalse = anotherList.every(i=> wordsList.includes(i));
console.log(trueOrFalse) //false

Find text (child text nodes) and wrap it in a paragraph

I need a function that finds text (child text nodes) inside some (for this example the div) elements and wraps the text in a paragraph.
Text1
<div>
<div>
Text2
<div>Text3</div>
</div>
<div>Text4</div>
<p>Text5</p>
</div>
<div>Text6</div>
<div>
Text7
<p>Text8</p>
Text9
</div>
tried did it like this:
const fn = (doc) => {
const coll = [...doc.childNodes];
coll.forEach(el => {
if (el.tagName === 'DIV' && el.childElementCount === 0) {
el.innerHTML = `<p>${el.innerHTML}</p>`;
}
if (el.childElementCount > 0) {
el.childNodes.forEach(item => {
if (item.nodeType === 3 && item.textContent.trim()) {
const content = item.textContent.trim();
item.innerHTML = `<p>${content}</p>`;
console.log('2: ', item.innerHTML);
}
});
fn(el);
}
});
}
but it works wrong - in if condition (el.childElementCount > 0) in console log, I got all needed nodes in p tags. but not in result. item.innerHTML = `<p>${content}</p>`; not apply it to document :(.
Can anyone help to fix it?
result i need:
Text1
<div>
<div>
<p>Text2</p>
<div><p>Text3</p></div>
</div>
<div><p>Text4</p></div>
<p>Text5</p>
</div>
<div><p>Text6</p></div>
<div>
<p>Text7</p>
<p>Text8</p>
<p>Text9</p>
</div>
You can use replaceWith() to replace the text node with the paragraph element
function filterTextNode(node) {
var textNodes = [];
for (node = node.firstChild; node; node = node.nextSibling) {
if (node.nodeType == 3 && node.textContent.trim()) textNodes.push(node);
else textNodes = textNodes.concat(filterTextNode(node));
}
return textNodes;
}
function wrapTextNode(text) {
var p = document.createElement('p');
p.innerHTML = text.textContent;
text.replaceWith(p);
}
const fn = (doc) => {
var textNodes = filterTextNode(doc);
textNodes.forEach(text => {
if (text.parentNode.tagName != 'P') {
wrapTextNode(text);
}
});
}
fn(document.body)
p {
color: red;
}
Text1
<div>
<div>
Text2
<div>Text3</div>
</div>
<div>Text4</div>
<p>Text5</p>
</div>
<div>Text6</div>
<div>
Text7
<p>Text8</p>
Text9
</div>
References
Find all text nodes in HTML page
https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith
By considering the childElementCount of the div we can get your desired result. Rewrite your function like below.
const fn = (document) => {
let elements = document.getElementsByTagName('div');
elements = Array.prototype.slice.call(elements);
elements.forEach(el => {
if (el.innerHTML && el.childElementCount === 0) {
el.innerHTML = `<p>${el.innerHTML}</p>`;
}
});
}
var elements = document.getElementsByTagName('div');
for(var i=0;i<elements.length;i++){
if(elements[i]===0){
console.log(elements[i].textContent);
}
else{
var y=elements[i].innerHTML
console.log(y)
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>testing result</title>
</head>
<body>
<div>Text1</div>
<div>
<div>Text2</div>
<p>Text3</p>
</div>
<div>Text4</div>
</body>
</body>
</html>
i tryed this but i cant get last two div(4 and 2) like this output in the console <div>text4</div> and <div>text2</div> i hope this my help and i dont know how to print last two div innerHTML

How can I display four images randomly with link and without duplicates using Javascript?

I'm trying to display four images randomly with a related link, by avoiding to display duplicated images each time. I've found how to randomly display a random image with the link, but I have no idea how to create the loop part and how to check for duplicates. I would appreciate your help.
<script>
function random_imglink(){
var myimages=new Array()
myimages[1]="image1.gif"
myimages[2]="image2.gif"
myimages[3]="image3.gif"
myimages[4]="image4.gif"
myimages[5]="image5.gif"
myimages[6]="image6.gif"
var imagelinks=new Array()
imagelinks[1]="http://www.page1.com"
imagelinks[2]="http://www.page2.com"
imagelinks[3]="http://www.page3.com"
imagelinks[4]="http://www.page4.com"
imagelinks[5]="http://www.page5.com"
imagelinks[6]="http://www.page6.com"
var ry=Math.floor(Math.random()*myimages.length);
if (ry==0)
ry=1;
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>');
}
random_imglink()
</script>
Thanks in advance :)
As stated on this answer, you can create a method for checking of duplicates.
method:
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
usage:
var imagelinks= [0,1,2],
index = contains.call(imagelinks, imagelinks[ry]); //boolean
Outside of your function, declare an array to hold elements that are already displayed:
var displayed = [];
Then after your if (ry==0) condition add this:
if (displayed.indexOf(ry) !== -1){
displayed.push(ry);
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>');
} else {
random_imglink();
}
You should learn about Constructors. When you call new on them they return an Object which has separate properties based on the Constructor. Below is some code that will help you along your journey.
//<![CDATA[
// external.js
var doc, bod, htm, C, E, inArray, ShuffleMagic; // for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
inArray = function(needle, haystack){
for(var i=0,l=haystack.length; i<l; i++){
if(haystack[i] === needle){
return true;
}
}
return false;
}
function ShuffleMagic(haystack){
var a;
this.haystack = haystack;
this.alterOriginal = false;
this.shuffle = function(limit){
var r, s = this.haystack;
if(!a){
a = [].slice.call(s), l = a.length;
for(var i=0,n=1,f,h; i<l; i++,n++){
f = Math.floor(Math.random()*n); h = a[i]; a[i] = a[f]; a[f] = h;
}
}
if(limit){
if(a.length >= limit){
r = a.splice(0, limit);
if(a.length < limit)a = undefined;
}
else{
a = undefined;
return this.shuffle(s.length);
}
}
else{
r = a; a = undefined;
}
if(this.alterOriginal){
s.splice.apply(s, [0, s.length].concat(r)); a = undefined;
}
return r;
}
}
var imagelinks = ['http://www.page1.com', 'http://www.page2.com', 'http://www.page3.com', 'http://www.page4.com', 'http://www.page5.com', 'http://www.page6.com', 'http://www.page7.com', 'http://www.page8.com', 'http://www.page9.com',
'http://www.page10.com', 'http://www.page11.com', 'http://www.page12.com', 'http://www.page13.com', 'http://www.page14.com', 'http://www.page15.com', 'http://www.page16.com', 'http://www.page17.com', 'http://www.page18.com', 'http://www.page19.com'];
var max = E('limit'), out = E('out');
var wow = new ShuffleMagic(imagelinks);
// wow.alterOriginal = true;
// wow.haystack = ['Replace', 'other', 'array, 'example'];
E('testButton').addEventListener('click', function(){
out.innerHTML = wow.shuffle(+max.value).join('<br />');
});
});
//]]>
/* external.css */
html,body{
margin:0; padding:0;
}
.main{
width:980px; margin:0 auto;
}
#limit{
width:30px; padding-left:3px;
}
<!DOCTYPE html>
<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>Shuffle Magic</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='test.js'></script>
</head>
<body>
<div class='main'>
<label for='limit'>Limit:</label><input id='limit' name='limit' type='text' value='4' /><input id='testButton' type='button' value='Click Me' />
<div id='out'></div>
</div>
</body>
</html>
With this version, which is recursive (probably beyond your understanding right now), the array elements only recycle once they've been completely or nearly completely gone through. Enjoy!

How to design a drop-down in button using css?

//id define
var id = function (name) {
return{
element : document.getElementById(name),
html : function (data) {
var ids = this.element;
if (data != undefined) {ids.innerHTML=data;}
else{return ids.innerHTML;}},
val : function (data) {
var ids = this.element;
if (data != undefined) {ids.value=data;}
else{return ids.value;}},
hide : function () {this.element.style.display="none";},
show : function () {this.element.style.display="block";},
clsremove : function (data) {this.element.classList.remove(data);},
clsadd : function (data) {this.element.classList.add(data);},
tex : function (data) { var latex = data.replace(/\^/g, "");
var latex_form = latex.replace(/([a-z])(\d+)/g,
function myFunction(tot,c1,c2) {var tag=(c1 =='^'?'sup':'sup');return c1+'<'+tag+'>'+c2+'</'+tag+'>';});
this.element.innerHTML= latex_form;
}
}
}
//class define
var cls = function (name) {
return{
element : document.getElementsByClassName(name),
html : function (data) {
var ids = this.element;
for (var i=0; i<ids.length; i++) {
if (data != undefined) {ids[i].innerHTML=data;}
else{return ids[i].innerHTML;}}},
val : function (data) {
var ids = this.element;
for (var i=0; i<ids.length; i++) {
if (data != undefined) {ids[i].value=data;}
else{return ids[i].value;}}},
hide : function () { var ids = this.element;for (var i=0; i<ids.length; i++) {ids[i].style.display="none";}},
show : function () {var ids = this.element;for (var i=0; i<ids.length; i++) {ids[i].style.display="block";}},
tex : function (data) { var latex = data.replace(/\^/g, "");
var latex_form = latex.replace(/([a-z])(\d+)/g,
function myFunction(tot,c1,c2) {var tag=(c1 =='^'?'sup':'sup');return c1+'<'+tag+'>'+c2+'</'+tag+'>';});
this.element.innerHTML= latex_form;
}
}
}
<!DOCTYPE html>
<html>
<head>
<script src="jfile/myquery.js"></script>
<script src="steps.js"></script>
</head>
<body>
<input id="myInput" type="text" value="20x+5k-10p-y=0">
<button onclick="checkFruit()">Check Fruit</button>
<p id="equ1"></p>
<p id="equ2"></p>
<p id="equ3"></p>
<p id="equ4"></p>
<p id="equ5"></p>
<p id="equ1p"></p>
<p id="equ2p"></p>
<p id="equ3p"></p>
<p id="equ4p"></p>
<p id="equ5p"></p>
<p id="xoneans1"></p>
<p id="xoneans2"></p>
<p id="xoneans3"></p>
<p id="xoneans4"></p>
<p id="xoneans5"></p>
<p id="xoneans6"></p>
<p id="xoneans7"></p>
<p id="xoneans8"></p>
<p id="xoneans9"></p>
<p id="xoneans10"></p>
<script>
function checkFruit() {
var reg =/([\-+])?\s*(\d+)?([a-zA-Z])\b/g;
var equation = id("myInput").val();
var spli= reg.exec(equation);
alert(spli);
var text;
var y= document.getElementById("myInput").value;
switch(y) {
case "20x+5k-10p-y=0":
ans = "First add both side for -20";
ans1= "Both side added by 10p";
ans2= "Next both side added by y";
ans3= "Divide by both side 5";
ans4= "Solution for k value";
document.getElementById("equ1").innerHTML = ans;
document.getElementById("equ2").innerHTML = ans1;
document.getElementById("equ3").innerHTML = ans2;
document.getElementById("equ4").innerHTML = ans3;
document.getElementById("equ5").innerHTML = ans4;
break;
case "20x+5k-10p-y=0p":
ans5p = "First add both side for -20";
ans6p= "Both side added by -5k";
ans7p= "Next both side added by y";
ans8p= "Divide by both side -10";
ans9p= "Solution for p value";
document.getElementById("equ1p").innerHTML = ans5p;
document.getElementById("equ2p").innerHTML = ans6p;
document.getElementById("equ3p").innerHTML = ans7p;
document.getElementById("equ4p").innerHTML = ans8p;
document.getElementById("equ5p").innerHTML = ans9p;
break;
case "20x+5k-10p-y=0x":
xone1 = "First add both side for -5";
xtwo2= "Both side added by 10p";
xthr3= "Next both side added by y";
xfour4= "Divide by both side 20";
xfive5= "Solution for x value";
document.getElementById("xoneans1").innerHTML = xone1;
document.getElementById("xoneans2").innerHTML = xtwo2;
document.getElementById("xoneans3").innerHTML = xthr3;
document.getElementById("xoneans4").innerHTML = xfour4;
document.getElementById("xoneans5").innerHTML = xfive5;
break;
case "20x+5k-10p-y=0y":
xone6 = "First add both side for -20";
xtwo7= "Both side added by -5k";
xthr8= "Next both side added by 10p";
xfour9= "Divide by both side -1";
xfive10= "Solution for y value";
document.getElementById("xoneans6").innerHTML = xone6;
document.getElementById("xoneans7").innerHTML = xtwo7;
document.getElementById("xoneans8").innerHTML = xthr8;
document.getElementById("xoneans9").innerHTML = xfour9;
document.getElementById("xoneans10").innerHTML = xfive10;
break;
// add the default keyword here
}
}
</script>
<p id="super"></p>
</body>
</html>
I have some code in the linear equation steps. How can I allow the user to open the drop-down list, and select a single letter, for which my code will then show the corresponding algorithm steps?
For example, I would like to display the menu
[x
y
z
p]
from that button, the user selects x, and my code should display the steps listed in the switch case for x.

Javascript / Jquery+ Replace single and double quotes in a inner html content

Let's say I have a DIV as below.
<div id="mydiv">
<p class="abc">some text here</p>
<p class="xyz"><img src="img.jpg" title="my img"/> some "double quoted text" here</p>
</div>
I read the inner html of the div.
var originalcontent = $("mydiv").html();
Now I need to replace double quotes for the texts only but not for the tag attributes. So my output should be as below.
var myoutput = '<p class="abc">some text here</p><p class="xyz"><img src="img.jpg" title="my img"/> some "double quoted text" here</p>'
Can you suggest me a solution please. Thank you!
Try this:
function replace_text(node){
node = node || document.getElementById('mydiv'); // Change 'mydiv' if you need
var children = node.childNodes;
var i = 0;
while(node = children[i]){ // While-loop
if (node.nodeType == 3){ // Some text, replace
if (node.textContent) { // Not IE (IE's equivalent to textContent is nodeValue)
node.textContent = node.textContent.replace(/"/g, '"');
}
else { // IE
node.nodeValue = node.nodeValue.replace(/"/g, '"');
}
} else { // not text, take step further
replace_text(node);
}
i++;
}
} // While-loop
// Don't forget to call function
replace_text();
With Jquery You can do this :
String.prototype.replaceAll = function(stringToFind,stringToReplace){
var temp = this;
var index = temp.indexOf(stringToFind);
while(index != -1){
temp = temp.replace(stringToFind,stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
$(function(){
$("#mydiv").children().each(function(){
var text=$(this).text();
text=text.replaceAll("\"",""");
//alert(text);
$(this).text(text);
});
});

Categories