I have a random image script, which displays random images on each page load. I want to add Next, Previous and Random buttons to this script, but don't know how to implement them.
Here's the Script
<script type="text/javascript">
var Statements = new Array(
'<img src="http://4.bp.blogspot.com/_UdzqQpb36Jo/R9kVS0h1BFI/AAAAAAAAD_o/SRGugAQSF0A/s1600/timming_pictures_37.jpg" height="650" width="625">',
'<img src="http://4.bp.blogspot.com/_UdzqQpb36Jo/SCxOksTrn4I/AAAAAAAAFDg/q3RilNGj9kc/s1600/loving_husbands_03.jpg" height="650" width="625">',
'<img src="http://3.bp.blogspot.com/_lCRnsgTQgRo/Se2KNaw6bpI/AAAAAAAAA5c/yV2PCN0Pmyo/s1600/pic22806.jpg" height="650" width="625">',
'<img src="http://1.bp.blogspot.com/_lCRnsgTQgRo/Se2J4mZjNEI/AAAAAAAAA4s/Q6Z8IlWLS-A/s1600/pic14006.jpg" height="650" width="625">'
);
function GetStatement(outputtype)
{
if(++Number > Statements.length - 1) Number = 0;
if (outputtype==0)
document.write(Statements[Number])
else if (document.getElementById)
document.getElementById("ponder").innerHTML=Statements[Number];
}
function GetRandomNumber(lbound, ubound)
{
return (Math.floor(Math.random() * (ubound - lbound)) + lbound);
}
var Number = GetRandomNumber(0, Statements.length - 1);
</script>
<script type="text/javascript">
GetStatement(0)
</script>
PS. I am using this script in blogger blog as blogpost.
Based on the request from first my answer, here the code:
HTML code:
<body onload="showPicNo(a)">
<div id="picture"><img name="picturegallery"></div>
<div id="navigation">
Backward |
Forward |
Share site
</div>
<body>
And the modifed Javascript code:
/*
The array 'pics' contains all adresses of picture you want to show. Scrope: global
*/
var pics=new Array (
"https://www.gravatar.com/avatar/9be5d328127c377109b295b5941733fb?s=32&d=identicon&r=PG",
"https://www.gravatar.com/avatar/1e81ddcda5d50a39c2beeaba3797702a?s=32&d=identicon&r=PG&f=1",
"https://www.gravatar.com/avatar/f47359966d28f2e603b6f759855970db?s=32&d=identicon&r=PG&f=1",
"https://www.gravatar.com/avatar/7d1a2026b0dca412b04ec548397b37f6?s=32&d=identicon&r=PG"
);
/*
The variable to used as the minimum number of elements and container for the current picture.
Because we work with an array, the index from first array element is zero.
Scope: global
*/
var a = 0;
/*
The variabe that used as the maximum number of showed pictures.
Here: The number of elements from array 'pics'. Scrope: global
*/
var b = pics.length;
/*
The current url that contains the adressbar from browser. Scope: global
*/
var currentUrl = document.URL;
/*
---------------------------------------------------------------------------------
Initial quicktest, if the parameter 'picnoprogram' does exits.
The parameter 'picnoprogram' is used parallel as an indicator and
as persistance layer.
Scope: global
*/
var existsPicParameter = currentUrl.match(/picnoparam\S*/i);
/*
Some helper variables. Scope: global
*/
var tmpPicParameter, tmpPicParameterOld;
/*
First requirement: If the page was loaded at the first time, it shall be show a
random picture from all available pictures.
The value of variable 'existsPicParamete' will be Null, if the parameter does not
exists in the adress bar; else a list of elements will be stored in there.
*/
if (existsPicParameter != null)
{
/*
So the page wasn't been loaded at first time.
We need the index from the last showed picture.
*/
tmpPicParameter = existsPicParameter[0].match(/picnoparam=\d+/i);
if (tmpPicParameter != null)
{
/*
Extracting the index from string
*/
a = parseInt(tmpPicParameter[0].match(/\d+/i));
tmpPicParameterOld = tmpPicParameter[0];
}
} else {
/*
So the page was loaded at the first time.
Generate a random number, within the declared range.
*/
a = Math.floor(Math.random() * (b - a)) + a;
}
/*
End of the initial quicktest
---------------------------------------------------------------------------------
*/
/*
The javascript function for forward scrolling.
It needs an explicit call.
*/
function fw()
{
if (a == (b - 1))
{
/*
The index of last array element is the array length minus 1.
Then reset the counter variable.
*/
a = 0;
} else {
a++;
}
navigate(a);
}
/*
The javascript function for backward scrolling.
It needs an explicit call.
*/
function bw()
{
if (a == 0)
{
a = b - 1;
} else {
a--
}
navigate(a);
}
/*
The javascript function that modified the page url
*/
function navigate(a)
{
if (existsPicParameter == null)
{
if (currentUrl.indexOf("?") == -1)
{
currentUrl += "?";
} else {
/*
In case there were already one or more url parameters,
the seporerator for another one is '&'
*/
currentUrl += "&";
}
/*
Extend the current url with parameter 'picnoprogram'.
*/
currentUrl += "picnoparam="+a;
} else {
/*
Update the current parameter value in the adressbar with the new one,
by replacing.
Only if the parameter 'picnoprogram' had been alerady exist
*/
tmpPicParameter[0] = tmpPicParameter[0].replace(/\d+/i,a);
currentUrl = currentUrl.replace(tmpPicParameterOld,tmpPicParameter[0]);
}
/* "Reload the site" */
window.location.replace(currentUrl);
}
/*
The javascript function for assigning the stored url to the HTML element 'img'.
It needs an explicit call.
*/
function showPicNo(picNumber)
{
window.document.images["picturegallery"].src=pics[picNumber];
}
/*
The javascript function that uses the share service from facebook.
See: http://stackoverflow.com/questions/13223951/facebook-share-button-how-to-implement .
It needs an explicit call.
*/
function shareButton()
{
/*
This ist the main part of the solution
*/
var facebooksUrlForSharingSites = 'https://www.facebook.com/sharer/sharer.php?u='
facebooksUrlForSharingSites += document.URL;
/*
An example way how to transfer the sharing data
*/
window.open(facebooksUrlForSharingSites,450,420);
}
Hopefully it meets your requirement.
I don't know your surrounding HTML code. In my eyes you should throw away your code.
Here a simple image gallery that should meet your requirements:
HTML code:
<html>
<head>
<meta http-equiv="expires" content="0">
</head>
<body onload="randomStartPic()">
<div id="picture"><img name="picturegallery"></div>
<div id="navigation">
Backward | Forward
</div>
<body>
</html>
And the Javascript code:
var pics=new Array ("http://4.bp.blogspot.com/_UdzqQpb36Jo/R9kVS0h1BFI/AAAAAAAAD_o/SRGugAQSF0A/s1600/timming_pictures_37.jpg", ...)
var a=0, b = pics.length;
function fw()
{
if (a == (b - 1))
{
a = 0;
} else {
a++;
}
showPicNo(a);
}
function bw()
{
if (a == 0)
{
a = b - 1;
} else {
a--;
}
showPicNo(a);
}
function randomStartPic()
{
a = Math.floor(Math.random() * (b - a)) + a;
showPicNo(a);
}
function showPicNo(picNumber)
{
window.document.images["picturegallery"].src=pics[picNumber];
}
At my local computer it did work perfectly...
Related
I am really bad at JavaScript hence need help. I am trying to assemble the final layout based on some conditions.
My question : I know the JavaScript is totally wrong. I am looking for the correct syntax and statement to get that content from multiple files and append them to respective divs.
Please note: I am not looking for any jQuery solutions as this is the only JavaScript Function in my template, and I don't want to load an entire Library for it.
My index.php file
<script type="text/javascript">
function loadLayout(){
var xmlhttp;
if (window.XMLHttpRequest)
{xmlhttp=new XMLHttpRequest();}
else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{document.getElementById("header").innerHTML=xmlhttp.responseText;}
{document.getElementById("body").innerHTML=xmlhttp.responseText;}
{document.getElementById("footer").innerHTML=xmlhttp.responseText;}
}
var
x=window.innerWidth||document.documentElement.clientWidth||document.getElementsByTagName.clientWidth;
if (x <= 800) {
xmlhttp.open("GET","header1.php",true); // this should append to Div with ID "header"
} else if (x > 800 && x <=1200) {
xmlhttp.open("GET","body1.php",true); // this should append to Div with ID "body"
} else if (x >1200) {
xmlhttp.open("GET","footer1.php",true);// this should append to Div with ID "footer"
}
xmlhttp.send();
}
window.onload = loadLayout; // When the page first loads
window.onresize = loadLayout; // When the browser changes size
</script>
<div id="header"></div>
<div id="body"></div>
<div id="footer"></div>
My header.php file
if ($xyz == '20' && $xyz <= '60'){
require_once 'some-1.php';
}
My body.php file
if ($xyz == '20' && $xyz <= '60'){
require_once 'some-2.php';
}
My footer.php file
if ($xyz == '20' && $xyz <= '60'){
require_once 'some-3.php';
}
The code below (fully commented) should help you:
/* we put all your code inside an IIFE, so we don't pollute the global scope */
(function() {
/* our AJAX helper function */
function ajax(url, callback, method) {
if (!method) method = 'GET';
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.addEventListener('load', function() {
callback.call(xhr, xhr.responseText);
});
xhr.send();
}
/* we create a variable to store our current layout
(so, we only make the AJAX request if the layout has changed) */
var lastLayout = [];
function loadLayout() {
/* we get the current width (didn't change your code) */
var width = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName.clientWidth;
/* and then, we use check what layout we must load */
var layout = width <= 800 ? ['body'] : width <= 1200 ? ['header', 'body'] : ['header', 'body', 'footer'];
/* if the new layout is different from the last loaded */
if (lastLayout.toString() !== layout.toString()) {
/* firstly, we set our current loaded to the new one */
lastLayout = layout;
/* we empty all the divs */
document.getElementById('header').innerHTML = '';
document.getElementById('body').innerHTML = '';
document.getElementById('footer').innerHTML = '';
/* loop through the layout divs that should be loaded */
layout.forEach(function(str) {
/* we use the variable to dinamically open the correct PHP file */
ajax(str + '1.php', function(result) {
/* and then, we use the variable again to fill the correct div */
document.getElementById(str).innerHTML = result;
});
});
}
}
window.onload = window.onresize = loadLayout;
})();
Ok so I've revised the markup/code to make it easier to understand. Using JavaScript I want to know how to create a text slider that changes a paragraph in html5 either "forwards" or "backwards" on click?
I only want one div to show at a time and the first div (div_1) needs to be visible at the beginning as a default setting. I also want to be able to add more text divs to it in the future. I'm new to JavaScript so I want to keep it as simple as possible.
I've had a go creating it in JavaScript which hasn't worked, I'm not sure if I'm going about this the right way.
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
.showHide {
display: none;
}
</style>
<script type="text/javascript">
var sdivs = [document.getElementById("div_1"),
document.getElementById("div_2"),
document.getElementById("div_3"),
document.getElementById("div_4")];
function openDiv(x) {
//I need to keep div_1 open as a starting point
sdivs[0].style.display ="block";
var j;
for (var j = 0; j < sdivs.length; j++) {
if (j === x) {
continue;
}
else {
sdivs[j].style.display = "none";
}
}
}
</script>
<title>text</title>
</head>
<body>
forward
backwards
<div id="text_holder">
<div id="div_1" class="showHide">One</div>
<div id="div_2" class="showHide">Two</div>
<div id="div_3" class="showHide">Three</div>
<div id="div_4" class="showHide">Four</div>
</div>
</body>
</html>
When dealing with multiple elements like this, I've found CSS alone to be insufficient (though its brilliant for modifying simple hover states or whatever). This one method here is pretty simple and specific to this one set of markup (so modify as you see fit). More importantly - its to illustrate how to set up a simple javascript "class" to handle your logic.
http://jsfiddle.net/1z13qb58/
// use a module format to keep the DOM tidy
(function($){
// define vars
var _container;
var _blurbs;
var _blurbWidth;
var _index;
var _clicks;
// initialize app
function init(){
console.log('init');
// initialize vars
_container = $('#text_holder .inner');
_blurbs = $('.blurb');
_blurbWidth = $(_blurbs[0]).innerWidth();
_clicks = $('.clicks');
_index = 0;
// assign handlers and start
styles();
addEventHandlers();
}
// initialize styles
function styles(){
_container.width(_blurbs.length * _blurbWidth);
}
// catch user interaction
function addEventHandlers(){
_clicks.on({
'click': function(el, args){
captureClicks( $(this).attr('id') );
}
});
}
// iterate _index based on click term
function captureClicks(term){
switch(term){
case 'forwards':
_index++;
if(_index > _blurbs.length - 1){
_index = 0;
}
break;
case 'backwards':
_index--;
if(_index < 0){
_index = _blurbs.length - 1;
}
break;
}
updateView();
}
// update the _container elements left value
function updateView(){
//_container.animate({
//'left' : (_index * _blurbWidth) * -1
//}, 500);
_container.css('left', ((_index * _blurbWidth) * -1) + 'px');
}
init();
})(jQuery);
I'm using jQuery to handle event binding and animation, but, again - there are lots of options (including a combination of vanilla javascript and CSS3 transitions).
I'll note also that this is all html4 and css2 (save your doctype).
Hopefully that helps -
A documented restriction with document and sheet add-ons is that Apps Script cannot tell what a user does outside of the add-on. This tantalizing tip is given:
It is possible to poll for changes in a file's contents from a
sidebar's client-side code, although you'll always have a slight
delay. That technique can also alert your script to changes in the
user's selected cells (in Sheets) and cursor or selection (in Docs).
Sadly, this isn't shown in any of the demo code. How can I do it?
The polling is done from the html code in your add-on's User Interface, calling across to server-side Apps Script functions using google.script.run.
Using jQuery simplifies this, and we can even start with the answers from jQuery, simple polling example.
function doPoll(){
$.post('ajax/test.html', function(data) {
alert(data); // process results here
setTimeout(doPoll,5000);
});
}
The basic idea can work for Google Apps Script, if we replace the ajax calls with the GAS equivalents.
Here's the skeleton of the poll function that you would use in your html file:
/**
* On document load, assign click handlers to button(s), add
* elements that should start hidden (avoids "flashing"), and
* start polling for document updates.
*/
$(function() {
// assign click handler(s)
// Add elements that should start hidden
// Start polling for updates
poll();
});
/**
* Poll a server-side function 'serverFunction' at the given interval
* and update DOM elements with results.
*
* #param {Number} interval (optional) Time in ms between polls.
* Default is 2s (2000ms)
*/
function poll(interval){
interval = interval || 2000;
setTimeout(function(){
google.script.run
.withSuccessHandler(
function(results) {
$('#some-element').updateWith(results);
//Setup the next poll recursively
poll(interval);
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.serverFunction();
}, interval);
};
Add-on Example, Document Poller
This is a demonstration of the jQuery polling technique calling server-side Google Apps Script functions to detect user behavior in a Google Document. It does nothing useful, but it showcases a few things that would typically require knowledge of the user's activity and state of the document, for instance context-sensitve control over a button.
The same principle could apply to a spreadsheet, or a stand-alone GAS Web Application.
Like the UI App example in this question, this technique could be used to get around execution time limits, for operations with a User Interface at least.
The code builds upon the example add-on from Google's 5-minute quickstart. Follow the instructions from that guide, using the code below instead of that in the quickstart.
Code.gs
/**
* Creates a menu entry in the Google Docs UI when the document is opened.
*
* #param {object} e The event parameter for a simple onOpen trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode.
*/
function onOpen(e) {
DocumentApp.getUi().createAddonMenu()
.addItem('Start', 'showSidebar')
.addToUi();
}
/**
* Runs when the add-on is installed.
*
* #param {object} e The event parameter for a simple onInstall trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode. (In practice, onInstall triggers always
* run in AuthMode.FULL, but onOpen triggers may be AuthMode.LIMITED or
* AuthMode.NONE.)
*/
function onInstall(e) {
onOpen(e);
}
/**
* Opens a sidebar in the document containing the add-on's user interface.
*/
function showSidebar() {
var ui = HtmlService.createHtmlOutputFromFile('Sidebar')
.setTitle('Document Poller');
DocumentApp.getUi().showSidebar(ui);
}
/**
* Check if there is a current text selection.
*
* #return {boolean} 'true' if any document text is selected
*/
function checkSelection() {
return {isSelection : !!(DocumentApp.getActiveDocument().getSelection()),
cursorWord : getCursorWord()};
}
/**
* Gets the text the user has selected. If there is no selection,
* this function displays an error message.
*
* #return {Array.<string>} The selected text.
*/
function getSelectedText() {
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var text = [];
var elements = selection.getSelectedElements();
for (var i = 0; i < elements.length; i++) {
if (elements[i].isPartial()) {
var element = elements[i].getElement().asText();
var startIndex = elements[i].getStartOffset();
var endIndex = elements[i].getEndOffsetInclusive();
text.push(element.getText().substring(startIndex, endIndex + 1));
} else {
var element = elements[i].getElement();
// Only translate elements that can be edited as text; skip images and
// other non-text elements.
if (element.editAsText) {
var elementText = element.asText().getText();
// This check is necessary to exclude images, which return a blank
// text element.
if (elementText != '') {
text.push(elementText);
}
}
}
}
if (text.length == 0) {
throw 'Please select some text.';
}
return text;
} else {
throw 'Please select some text.';
}
}
/**
* Returns the word at the current cursor location in the document.
*
* #return {string} The word at cursor location.
*/
function getCursorWord() {
var cursor = DocumentApp.getActiveDocument().getCursor();
var word = "<selection>";
if (cursor) {
var offset = cursor.getSurroundingTextOffset();
var text = cursor.getSurroundingText().getText();
word = getWordAt(text,offset);
if (word == "") word = "<whitespace>";
}
return word;
}
/**
* Returns the word at the index 'pos' in 'str'.
* From https://stackoverflow.com/questions/5173316/finding-the-word-at-a-position-in-javascript/5174867#5174867
*/
function getWordAt(str, pos) {
// Perform type conversions.
str = String(str);
pos = Number(pos) >>> 0;
// Search for the word's beginning and end.
var left = str.slice(0, pos + 1).search(/\S+$/),
right = str.slice(pos).search(/\s/);
// The last word in the string is a special case.
if (right < 0) {
return str.slice(left);
}
// Return the word, using the located bounds to extract it from the string.
return str.slice(left, right + pos);
}
Sidebar.html
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<!-- The CSS package above applies Google styling to buttons and other elements. -->
<div class="sidebar branding-below">
<form>
<div class="block" id="button-bar">
<button class="blue" id="get-selection" disabled="disable">Get selection</button>
</div>
</form>
</div>
<div class="sidebar bottom">
<img alt="Add-on logo" class="logo" height="27"
id="logo"
src="https://www.gravatar.com/avatar/adad1d8ad010a76a83574b1fff4caa46?s=128&d=identicon&r=PG">
<span class="gray branding-text">by Mogsdad, D.Bingham</span>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
/**
* On document load, assign click handlers to button(s), add
* elements that should start hidden (avoids "flashing"), and
* start polling for document selections.
*/
$(function() {
// assign click handler(s)
$('#get-selection').click(getSelection);
// Add elements that should start hidden
var newdiv1 = $( "<div class='block' id='cursor-word'/>" ).hide(),
newdiv2 = $( "<div class='block' id='selected-text'/>" ).hide();
$('#button-bar').after( newdiv1, newdiv2 );
$('#cursor-word').html('<H2>Word at cursor:</H2><p id="cursor-word-content"></p>');
$('#selected-text').html('<H2>Selected text:</H2><p id="selected-text-content"></p>');
// Start polling for updates
poll();
});
/**
* Poll the server-side 'checkSelection' function at the given
* interval for document selection, and enable or disable the
* '#get-selection' button.
*
* #param {Number} interval (optional) Time in ms between polls.
* Default is 2s (2000ms)
*/
function poll(interval){
interval = interval || 2000;
setTimeout(function(){
google.script.run
.withSuccessHandler(
function(cursor) {
if (cursor.isSelection) {
// Text has been selected: enable button, hide cursor word.
$('#get-selection').attr('disabled', false);
$('#cursor-word').hide();
// $('#selected-text').show(); // Not so fast - wait until button is clicked.
}
else {
$('#get-selection').attr('disabled', true);
$('#cursor-word').show();
$('#selected-text').hide();
}
$('#cursor-word-content').text(cursor.cursorWord);
//Setup the next poll recursively
poll(interval);
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.checkSelection();
}, interval);
};
/**
* Runs a server-side function to retrieve the currently
* selected text.
*/
function getSelection() {
this.disabled = true;
$('#error').remove();
google.script.run
.withSuccessHandler(
function(selectedText, element) {
// Show selected text
$('#selected-text-content').text(selectedText);
$('#selected-text').show();
element.disabled = false;
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.withUserObject(this)
.getSelectedText();
}
/**
* Inserts a div that contains an error message after a given element.
*
* #param msg The error message to display.
* #param element The element after which to display the error.
*/
function showError(msg, element) {
var div = $('<div id="error" class="error">' + msg + '</div>');
$(element).after(div);
}
</script>
Polling Interval
The setTimeout() function accepts a time interval expressed in milliseconds, but I found through experimentation that a two-second response was the best that could be expected. Therefore, the skeleton poll() has a 2000ms interval as its default. If your situation can tolerate a longer delay between poll cycles, then provide a larger value with the onLoad call to poll(), e.g. poll(10000) for a 10-second poll cycle.
Sheets
For a sheet example see How do I make a Sidebar display values from cells?
Very much a newbie here and wanting a bit of guidance.
I'm trying to create a project where you bind a key to start a timer then show an output in the results box. However i'm facing an issue where I need to create a new line if the user releases the bound button to start a new timer, however I can't find a way to start the timer again. Bear in mind within the time, a user could press the bound key over a hundred times, I don't want to manually create new lines and timer's.
My thoughts are creating a a random token, then on release, it creates a break, if the next line doesn't match this token it begins again.
Edit:So you can see, the value is based on the 2 variables, and even when I hold down the specific button again, it just adds to the current smallTime. I know this is how it's currently build, but i'm trying to get it to reset and go to the next line dynamically.
Any help would be greatly appreciated.
<html>
<head>
<textarea class="code_input" name="allInputs" id="textareaCode" wrap="logical" rows="10" cols="50" readonly="true"> </textarea>
<script type="text/javascript">
var shortSeconds = 0;
var shortmillisec = 0;
function buttonPressed(e) {
key = String.fromCharCode(e.keyCode).toLocaleLowerCase()
//alert (key)
keyInput = e.keyCode
if (withinTime == true && key == bind) {
shortDisplay()
shortTimerFunction();
}
}
function shortDisplay() {
if (shortmillisec >= 9) {
shortmillisec = 0
shortSeconds += 1
}
else
shortmillisec += 1
}
function startstoptimerShort() {
if (shortTimer > 0) {
clearTimeout(shortTimer);
shortTimer = 0;
} else {
withinTime = true
shortTimerFunction()
}
}
function shortTimerFunction() {
smallTime = shortSeconds + "." + shortmillisec;
shortTimer = setTimeout("shortTimerFunction()", 100);
//need to work out what line to put the output on
allInputs = document.getElementById('textareaCode')
allInputs.value = (textbox3.value) + (": " + smallTime) + '\n';
}
</script>
</body>
</html>
Basically I have a html page with hundreds of images on it each with a title attribute describing the image. Ideally I would change all this but the page has to stay as it is for now.
I want to search these title attributes and scroll the page to the corresponding image if possible. - I've played around with some javascript search scripts but cannot get it to work with straightforward "On page" searches as the tags are in the code rather than displayed on page.
Can anyone point me in the right direction on how to do something like this?
This was the "Search on page" code I was using
var n = 0;
function findInPage(str) {
var txt, i, found;
if (str == "") {
return false;
}
// Find next occurance of the given string on the page, wrap around to the
// start of the page if necessary.
if (window.find) {
// Look for match starting at the current point. If not found, rewind
// back to the first match.
if (!window.find(str)) {
while (window.find(str, false, true)) {
n++;
}
} else {
n++;
}
// If not found in either direction, give message.
if (n == 0) {
alert("Not found.");
}
} else if (window.document.body.createTextRange) {
txt = window.document.body.createTextRange();
// Find the nth match from the top of the page.
found = true;
i = 0;
while (found === true && i <= n) {
found = txt.findText(str);
if (found) {
txt.moveStart("character", 1);
txt.moveEnd("textedit");
}
i += 1;
}
// If found, mark it and scroll it into view.
if (found) {
txt.moveStart("character", -1);
txt.findText(str);
txt.select();
txt.scrollIntoView();
n++;
} else {
// Otherwise, start over at the top of the page and find first match.
if (n > 0) {
n = 0;
findInPage(str);
}
// Not found anywhere, give message. else
alert("Not found.");
}
}
return false;
}
You can select by html attribute.
Using plain JS (in modern browsers incl. IE8+):
document.querySelectorAll('[title*="my text"]')
Using jQuery:
$('[title*=my text]')
would find:
<img src="/path" title="this is a title with my text" />
From there, you would need to get the page position of the image returned by the selector, and then scroll your page to that point, optionally (likely) with some offset so it doesn't bang up against the top of the viewport
EDIT:
function findElementsByTitle(str) {
return document.querySelectorAll('[title*="' + str + '"]');
}
function scrollToElement(el) {
var yOffset = el.offset().top; //this is a jQuery method...you don't want to write this in plain JS
window.scrollTo(0, yOffset - 10) //params are x,y. the - 10 is just so your image has some "padding" in the viewport
}