scroll to top function on webpage - javascript

Hi I have a script I am using to search for words on a page and then bring them to the top of the page. My issue is I have a Fixed header and the highlighted results scroll under the fixed header. How can I fix the script to not go to top but to 300 px down from the top so the results are midway on page and highlighted?
Here is my code:
inPageSearch = function () {
document.getElementsByClassName = function (cl) {
var retnode, myclass, elem, classes;
retnode = [];
myclass = new RegExp('\\b' + cl + '\\b');
elem = this.getElementsByTagName('*');
for (var i = 0, ii = elem.length; i < ii; i++) {
classes = elem[i].className;
if (myclass.test(classes)) retnode.push(elem[i]);
}
return retnode;
};
elemTop = function (elem) {
return elem.top || elem.pixelTop || elem.offsetTop || 0;
};
search = function (str) {
nodewalk = function (node, str) {
var re, m, s, r, frag, sp;
for (var i = 0; i < node.length; i++) {
if (node[i].hasChildNodes() && 'SCRIPT' !== node[i].nodeName) nodewalk(node[i].childNodes, str);
re = new RegExp(str, 'ig');
if (3 === node[i].nodeType) {
m = node[i].nodeValue.match(re);
s = node[i].nodeValue.split(re);
frag = document.createDocumentFragment();
if (m !== null) {
frag.appendChild(document.createTextNode(s[0]));
for (var j = 0, jj = m.length; j < jj; j++) {
sp = document.createElement('span');
sp.appendChild(document.createTextNode(m[j]));
sp.className = 'found';
frag.appendChild(sp);
frag.appendChild(document.createTextNode(s[j + 1]));
}
node[i].parentNode.replaceChild(frag, node[i]);
i += jj * 2;
}
}
}
};
nodewalk(document.getElementsByTagName('body')[0].childNodes, str);
};
clearfound = function (node) {
var txt = node.previousSibling.nodeValue + node.firstChild.nodeValue + node.nextSibling.nodeValue;
node.parentNode.removeChild(node.nextSibling);
node.parentNode.removeChild(node.previousSibling);
node.parentNode.replaceChild(document.createTextNode(txt), node);
};
var d, F, fld, inp, b1, b2, b3;
d = document.createElement("div");
d.id = 'searchbox';
F = document.createElement("form");
fld = document.createElement("fieldset");
inp = document.createElement("input");
inp.type = 'text';
inp.id = 'search';
fld.appendChild(inp);
b1 = document.createElement("input");
b1.type = 'button';
b1.id = 'search1';
b1.value = 'Find';
b1.title = 'Find all and jump to first';
fld.appendChild(b1);
b2 = document.createElement("input");
b2.type = 'button';
b2.id = 'search2';
b2.value = 'Find Next';
b2.title = 'Jump to next found element';
fld.appendChild(b2);
b3 = document.createElement("input");
b3.type = 'button';
b3.id = 'searchx';
b3.value = 'X';
b3.title = 'Close in page search';
fld.appendChild(b3);
F.appendChild(fld);
d.appendChild(F);
document.getElementsByTagName('body')[0].appendChild(d);
document.getElementById('search1').onclick = function () {
var nodes = document.getElementsByClassName('found');
for (var i = nodes.length - 1; i >= 0; i--) clearfound(nodes[i]);
search(document.getElementById('search').value);
window.scrollTo(0, elemTop(document.getElementsByClassName('found')[0]));
return false;
};
document.getElementById('search2').onclick = function () {
var nodes = document.getElementsByClassName('found');
clearfound(nodes[0]);
window.scrollTo(0, elemTop(document.getElementsByClassName('found')[0]));
return false;
};
document.getElementById('searchx').onclick = function () {
var nodes = document.getElementsByClassName('found');
for (var i = nodes.length - 1; i >= 0; i--) clearfound(nodes[i]);
document.getElementById('searchbox').style.display = 'none';
setTimeout(function () {
document.getElementsByTagName('body' [0].removeChild(document.getElementById('searchbox'));
}, 5);
};
};
inPageSearch();

window.scrollTo(0,300); will scroll the page to 300px from the top.

Related

It always show either one output, either it highlight the keywords or only the alert box,how to achieve both at the same time

//grab all div elements in the pages;
let elt = document.getElementsByTagName("div");
var i;
var b = [];
b[0] = "password";
b[1] = "update";
b[2] = "account";
b[3] = "blocked";
b[4] = "alert";
b[5] = "confirm";
b[6] = "cash";
b[7] = "extra";
b[8] = "subscribe";
b[9] = "sample";
b[10] = "winner";
b[11] = "offer";
b[12] = "promotion";
b[13] = "urgent";
b[14] = "action";
b[15] = "update";
b[16] = "luxury";
b[17] = "limited";
b[18] = "login";
b[19] = "alert";
b[20] = "income";
b[21] = "bonus";
b[22] = "verify";
b[23] = "banking";
b[24] = "lowest";
b[25] = "deal";
b[26] = "unusual log in activity";
function scanDOM() {
//loop for html elements;
for (i = 0; i < elt.length; i++) {
var singleDiv = elt[i];
//loop for keywords;
for (j = 0; j < b.length; j++) {
var str = singleDiv.innerHTML;
if (str.indexOf(b[j]) > -1) {
//if found that the keywords match with the one in array, it will highlight the words;
str = str.replace(b[j], '<span style="background-color:#f6ff00;">' + b[j] + '</span>');
singleDiv.innerHTML = str;
popup();
}
}
}
}
// scan through the pages every 5 seconds;
setInterval(scanDOM, 5000);
//alert message;
function popup() {
alert * ("**WARNING!**");*
}

Javascript object that takes another object's property as parameter changes it somehow

I've been working on a Math Parser project. I'm almost finished but I encountered a problem that I couldn't find the reason for it.
I've got 3 javascript files:
main.js
var button1 = document.getElementById("button");
var text1 = document.getElementById("text");
var output = document.getElementById("result");
button1.addEventListener("click", function(){
var textInput = text1.value;
var cleared = new clearingUnwantedCharacters(textInput);
var marked = new subgroupMarking(cleared.output);
var prioritizedList = new subgroupPrioritization(marked.parenGroups);
for(var i = 0; i <= 360; i++){
var splittedPieces = new splittingOperators(prioritizedList.prioritizedGroups);
var calculatedPieces = new calculatePieces(splittedPieces.seperatedPieces, i, true);
console.log(calculatedPieces.result);
}
});
objects.js
function clearingUnwantedCharacters(inputText){
this.output = inputText;
this.output = this.output.replace(/\s+/g, '');
this.output = this.output.toLowerCase();
}
function subgroupMarking(inputText){
this.parenGroups = [inputText];
this.locLeftParen = markChar(this.parenGroups[0], "(");
this.locRigthParen = markChar(this.parenGroups[0], ")");
for(var i = this.locLeftParen.length-1; i >= 0; i--){
var leftParen = this.locLeftParen[i];
var rightParen = this.locRigthParen.find(function(res){return res > leftParen});
this.parenGroups[i+1] = this.parenGroups[0].substring(leftParen+1, rightParen);
this.parenGroups[0] = changeAt(this.parenGroups[0], leftParen, rightParen+1, "{_"+(i+1)+"}");
this.locLeftParen = markChar(this.parenGroups[0], "(");
this.locRigthParen = markChar(this.parenGroups[0], ")");
}
}
function subgroupPrioritization(subgroupList){
var withParenGroup = [];
var withoutParenGroup = [];
for(var i = 0; i < subgroupList.length; i++){
var content = subgroupList[i].toString();
var hasParenGroup = content.search(/{_\d+}/g);
if(hasParenGroup == -1){
withoutParenGroup.push(content);
}else{
withParenGroup.push(content);
}
}
this.prioritizedGroups = withParenGroup.concat(withoutParenGroup);
}
function splittingOperators(prioritizedGroupList){
this.seperatedPieces = [];
for(var i = prioritizedGroupList.length-1; i >= 0; i--){
var pieces = prioritizedGroupList[i].split(/(\+|\*|\/|\^|\b(?=-)|(?<=})(?=-))/g);
for(var k = 0; k < pieces.length; k++){
if(pieces[k] == ""){
pieces[k] = "+";
}
}
this.seperatedPieces.unshift(pieces);
}
}
function calculatePieces(pieceList, x, degreeOption){
this.result = pieceList;
for(var i = this.result.length-1; i >= 0; i--){ // ["34", "+", "2{_2}"]
for(var k = 0; k < this.result[i].length; k++){ // 34, +, 2{_2}
var specialFlag = false;
var totalMultiplication = (countChar(this.result[i][k], "-")%2 == 0) ? 1 : -1;
var has = {
x : this.result[i][k].includes("x"),
subgroup : (this.result[i][k].search(/{_\d+}/g) != -1),
logarithm : this.result[i][k].includes("log"),
trigonometry : (this.result[i][k].includes("sin") || this.result[i][k].includes("cos") || this.result[i][k].includes("tan") || this.result[i][k].includes("cot"))
};
if(has.trigonometry){
specialFlag = true;
var trigSubgroupIndexes = [];
var trigTypes = [];
var trigsMultiplied = 1;
this.result[i][k] = this.result[i][k].replace(/(?:arc)?(sin|cos|tan|cot){_(\d+)}/g, function(match, type, index){
trigSubgroupIndexes.push(parseInt(index));
if(match.includes("arc")){
trigTypes.push([true, type]);
}else{
trigTypes.push([false, type]);
}
return " ";
});
for(var l = 0; l < trigTypes.length; l++){
var inverseness = trigTypes[l][0];
var type = trigTypes[l][1];
var parameter = (degreeOption) ? convertToRadian(parseFloat(this.result[trigSubgroupIndexes[l]])) : parseFloat(this.result[trigSubgroupIndexes[l]]);
var result;
if(inverseness){
switch(type){
case "sin":
result = Math.asin(parameter);
break;case "cos":
result = Math.acos(parameter);
break;case "tan":
result = Math.atan(parameter);
break;case "cot":
result = 1 / Math.atan(parameter);
break;
}
}else{
switch(type){
case "sin":
result = Math.sin(parameter);
break;case "cos":
result = Math.cos(parameter);
break;case "tan":
result = Math.tan(parameter);
break;case "cot":
result = 1 / Math.tan(parameter);
break;
}
}
trigsMultiplied *= result;
}
totalMultiplication *= trigsMultiplied;
}
if(has.logarithm){
specialFlag = true;
var logSubgroupIndexes = [];
var logsMultiplied = 1;
this.result[i][k] = this.result[i][k].replace(/log{_(\d+)}{_(\d+)}/g, function(match, firstIndex, secondIndex){
logSubgroupIndexes.push([parseInt(firstIndex), parseInt(secondIndex)]);
return " ";
});
for(var l = 0; l < logSubgroupIndexes.length; l++){
var base = this.result[logSubgroupIndexes[l][0]];
var power = this.result[logSubgroupIndexes[l][1]];
logsMultiplied *= (Math.log(power) / Math.log(base));
}
totalMultiplication *= logsMultiplied;
}
if(has.subgroup){
specialFlag = true;
var subgroupIndexes = [];
var groupsMultiplied = 1;
this.result[i][k] = this.result[i][k].replace(/{_(\d+)}/g, function(match, index){
subgroupIndexes.push(parseInt(index));
return " ";
});
for(var l = 0; l < subgroupIndexes.length; l++){
groupsMultiplied *= this.result[subgroupIndexes[l]];
}
totalMultiplication *= groupsMultiplied;
}
if(has.x){
specialFlag = true;
var powerX = countChar(this.result[i][k], "x");
this.result[i][k] = this.result[i][k].replace("x", " ");
totalMultiplication *= Math.pow(x, powerX);
}
if(specialFlag == true){
var factors = this.result[i][k].match(/\d+/g);
if(factors !== null){
for(var l = 0; l < factors.length; l++){
totalMultiplication *= parseFloat(factors[l]);
}
}
if(!isFinite(totalMultiplication) || checkNum(this.result[i][k]) || this.result[i][k].includes("(") || this.result[i][k].includes(")")){
this.result[i][k] = NaN;
}else{
this.result[i][k] = totalMultiplication;
}
}
}
var operators = ["^","*","/","+","-"];
for(var k = 0; k < operators.length; k++){
var search = this.result[i].indexOf(operators[k]);
while(search != -1){
switch(operators[k]){
case "+":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) + checkParse(this.result[i][search+1]));
break;case "-":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) - checkParse(this.result[i][search+1]));
break;case "*":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) * checkParse(this.result[i][search+1]));
break;case "/":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) / checkParse(this.result[i][search+1]));
break;case "^":
this.result[i].splice(search-1, 3, Math.pow(checkParse(this.result[i][search-1]) , checkParse(this.result[i][search+1])));
break;
}
if(this.result[i].indexOf(operators[k], search) == -1){
break;
}else{
search = this.result[i].indexOf(operators[k], search);
}
}
}
}
if(isNaN(this.result[0][0])){
this.result = "An error has occured, please make sure the parameters are correct.";
}else{
this.result = this.result[0][0];
}
}
functions.js
function countChar(str, character){
return str.toString().split(character).length-1;
}
function markChar(str, character){
var charCount = str.split(character).length;
var result = [];
for(var i = 0; i < charCount - 1; i++){
if(result.length == 0){
result.push(str.indexOf(character));
}else{
result.push(str.indexOf(character, result[i-1] + 1));
}
}
return result;
}
function changeAt(str, startingIndex, endingIndex, replacement){ // Returns the given string with the part between startingIndex and endingIndex replaced with replacement.
return str.substring(0, startingIndex) + replacement + str.substring(endingIndex, str.length);
}
function checkParse(str){
if(/[a-z]/.test(str) || countChar(str, ".") > 1){
return NaN;
}else{
return parseFloat(str);
}
}
function checkNum(str){
return (/[a-z]/.test(str) || countChar(str, ".") > 1);
}
function convertToRadian(degrees) {
return degrees * Math.PI / 180;
}
It works as intended when done like above. It puts values to x according to the range specified in the for loop in main.js and console.logs the results. But I don't want to create splittingOperators object everytime I recalculate with another x value. It's unnecessary since the actual formula stays the same.
var button1 = document.getElementById("button");
var text1 = document.getElementById("text");
var output = document.getElementById("result");
button1.addEventListener("click", function(){
var textInput = text1.value;
var cleared = new clearingUnwantedCharacters(textInput);
var marked = new subgroupMarking(cleared.output);
var prioritizedList = new subgroupPrioritization(marked.parenGroups);
var splittedPieces = new splittingOperators(prioritizedList.prioritizedGroups);
for(var i = 0; i <= 360; i++){
var calculatedPieces = new calculatePieces(splittedPieces.seperatedPieces, i, true);
console.log(calculatedPieces.result);
}
});
When I put the object creation outside of the for loop, it calculates and logs the first x value, but it gives
Uncaught TypeError: this.result[i][k].includes is not a function
as error after that. I suspect it's because it changes splittedPieces.seperatedPieces when it shouldn't. I couldn't find any reason for it to do that or maybe I am missing something.

Why is SetTimeout not executing?

I'm trying to write a javascript bookmark that, based on the current URL, navigates you to another page. Then after that navigation is done, it looks for a particular ID tag then navigates you again.
I have the first navigation done and working:
javascript:
(function() {
ADCURL = "PageA.aspx";
var temp = window.location.href;
var tarr = temp.split("/");
var serv = "https://" + tarr[2];
var x = document.getElementsByTagName("html")[0].dir;
if (x) {
var x = document.getElementsByTagName("link");
for (i = 0; i < x.length; i++) {
var y = x[i].attributes[2].value;
var lookingfor = "_vti_bin";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(y)) {
var z = y.replace("_vti_bin/spsdisco.aspx", ADCURL);
var link = serv + z;
window.location.href = link;
}
}
} else {
DL5 = document.links;
for (lKi = 0; lKi < DL5.length; lKi++) {
map = DL5[lKi];
var lookingfor = "sites";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var lookingfor = "_layout";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {} else {
var lookingfor = "SharedDocuments";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var n = String(map).indexOf("SharedDocuments");
var x = String(map).slice(0, n);
var link = x + ADCURL;
window.location.href = link;
}
}
}
}
}
})();
however when I try to use a SetTimeout to delay the script so I can grab the ID i need from the page I navigated to, nothing happens (for now I just have a window alert in there as a placeholder until I get the SetTimeout to work):
javascript:
(function() {
ADCURL = "PageA.aspx";
var temp = window.location.href;
var tarr = temp.split("/");
var serv = "https://" + tarr[2];
var x = document.getElementsByTagName("html")[0].dir;
if (x) {
var x = document.getElementsByTagName("link");
for (i = 0; i < x.length; i++) {
var y = x[i].attributes[2].value;
var lookingfor = "_vti_bin";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(y)) {
var z = y.replace("_vti_bin/spsdisco.aspx", ADCURL);
var link = serv + z;
window.location.href = link;
}
}
} else {
DL5 = document.links;
for (lKi = 0; lKi < DL5.length; lKi++) {
map = DL5[lKi];
var lookingfor = "sites";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var lookingfor = "_layout";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {} else {
var lookingfor = "SharedDocuments";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var n = String(map).indexOf("SharedDocuments");
var x = String(map).slice(0, n);
var link = x + ADCURL;
window.location.href = link;
}
}
}
}
}
setTimeout(function(){window.alert("yes");}, 2000);
})();
Any ideas what's going on? When using javascript in bookmarks is it not possible to do what I'm trying to do?

Show same page after virtual form submission from javascript

I have this javascript function
function SaveData(index) {
var myVirtualForm = document.createElement("form");
myVirtualForm.setAttribute('method', "post");
var name = $("#" + index + " a").attr('name');
var url = "http://localhost/my_Project/communicator.php?command=save&id=" + name;
myVirtualForm.setAttribute('action', url);
var iframe = document.getElementById(index + "frame");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var oTable = innerDoc.getElementById("reporttable");
//alert(oTable.rows.item(0).cells.item(0).innerText);
//gets table
var str = "";
var rowLength = oTable.rows.length;
//gets rows of table
for (i = 0; i < rowLength; i++) {
//loops through rows
var oCells = oTable.rows.item(i).cells;
var cellLength = oCells.length;
for (var j = 0; j < cellLength; j++) {
var cellVal = oCells.item(j).innerText;
var a = "";
var b = a.concat(i.toString(), "_", j.toString());
var obj = document.createElement("input");
obj.setAttribute('type', "text");
obj.setAttribute('name', b);
obj.setAttribute('value', cellVal.toString())
myVirtualForm.appendChild(obj);
}
}
myVirtualForm.submit();
}
After submission we go to communicator.php, but i want to stay on same page, who will not changed.

Global variable doesn't change with jquery function

I have a problem with my code. So I am trying to change the value of interval from 9 to the value of current_interval. This happens via a click event. But when the ChangePicture() function starts interval is still 9 (basically i have a picture rotator script that changes picture after 5 seconds).
var interval = 9;
var globalCounter = 0;
var temp = setInterval(function() {ChangePicture()}, 5000);
function SetInterval(i)
{
interval = i;
}
$(document).on("click", ".picture_button_lol", function(event){
var current_interval = $(this).children(".amount_of_pictures").val();
SetInterval(current_interval);
});
function ChangePicture()
{
var pictureId = globalCounter%interval;
ShowAndHide(pictureId);
globalCounter = globalCounter + 1;
}
function ShowAndHide(picId)
{
var picture = "bigview_" + picId;
var text = "bigview_text_" + picId;
var button = "bigview_button_" + picId;
var z_index = 1;
document.getElementById(picture).style.zIndex = z_index;
document.getElementById(text).style.zIndex = z_index;
document.getElementById(button).style.backgroundColor = "#ffffff";
document.write(interval);
for(var i=0; i<interval; i++)
{
if(i != picId)
{
picture = "bigview_" + i;
text = "bigview_text_" + i;
button = "bigview_button_" + i;
z_index = 0;
document.getElementById(picture).style.zIndex = z_index;
document.getElementById(text).style.zIndex = z_index;
document.getElementById(button).style.backgroundColor = "#000000";
}
}
globalCounter = picId;
}
You should trying using a callback :
function ChangePicture()
{
var pictureId = globalCounter%interval;
ShowAndHide(pictureId, function() {
globalCounter = globalCounter + 1;
});
}
function ShowAndHide(picId, callback)
{
var picture = "bigview_" + picId;
var text = "bigview_text_" + picId;
var button = "bigview_button_" + picId;
var z_index = 1;
document.getElementById(picture).style.zIndex = z_index;
document.getElementById(text).style.zIndex = z_index;
document.getElementById(button).style.backgroundColor = "#ffffff";
document.write(interval);
for(var i=0; i<interval; i++)
{
if(i != picId)
{
picture = "bigview_" + i;
text = "bigview_text_" + i;
button = "bigview_button_" + i;
z_index = 0;
document.getElementById(picture).style.zIndex = z_index;
document.getElementById(text).style.zIndex = z_index;
document.getElementById(button).style.backgroundColor = "#000000";
}
}
globalCounter = picId;
callback();
}

Categories