-1

In the page I have time and right of it some pictures. I wanna to create a button to jump to current time using Tampermonkey. Current time is a text in <h1>. You can see a screenshot below. time screen

code screen

How to jump to some position. For example 07:39. If you want to suggest external library, please show me how to use it in Tampermonkey.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
cask
  • 747
  • 1
  • 8
  • 13

2 Answers2

1

Finding H1 by XPath

If the document tree is stable (the order of elements is always the same) you can get the XPath and get the H1 element by xPath. That would be the fastest (in the mean of CPU time) solution.

Finding H1 with time in it

Otherwise, I'd use regular expression to detect time format in H1 element.

var headers = document.getElementsByTagName("h1");
//Regexp: Any amount of whitespace; One or two numbers; :; Two numbers; any ammount of whitespace
var check = /\s*[0-9]{1,2}:[0-9]{2}\s*/;
//Position
var pos = 0;
for(var i=0, l=headers.length;i<l;i++)
{
    if(check.test(headers[i].textContent))
    {
        pos = headers[i].offsetTop;
        //After finding the element, do not loop any more.
        break;
    }
}
//Scroll to pixel position [0; pos]
window.scrollTo(0,pos);

Getting specific time and finding it

If you want to jump to as specific time (eg. current time at any moment), go for the Date object. With that, you can do as follows:

var date = new Date();
var time_string = zeroFill(date.getHours())+":"+zeroFill(date.getMinutes());
//Procceed with the loop

Using the zeroFill function.

Community
  • 1
  • 1
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
0

Seems my javascript experience grows :)

var myList = document.getElementsByTagName("h1");
var time = "07:39";
for(var i=0;i<myList.length;i++)
{
    if(myList[i].textContent == time)
    {
        var pos = myList[i].offsetTop;
    }
}
window.scrollTo(0,pos);
cask
  • 747
  • 1
  • 8
  • 13
  • Yeah. I use it with button. Its working only after page is fully loaded. I have no another solution for now :( – cask Aug 30 '14 at 00:50
  • There are also some flaws to your code. First, you lack a `break` in your `for`, so it will loop even **after** finding the correct H1. Second, when no `H1` is found, you get an **undefined variable** error. – Tomáš Zato Aug 30 '14 at 01:05
  • I tryed to use `window.onload = function ()` to test if i pressed button before to load scroll again, but seems this functions not see my vars. – cask Aug 30 '14 at 01:40
  • Variable only lasts in the function where it was defined. What about other way around? Define global variable `var loaded = false` and set it to true in the onload event. – Tomáš Zato Aug 30 '14 at 10:13