[Tex/LaTex] Hyperlink to top of the page with given hypertarget

hyperreflinks

I need to create hyperlink that points to the top of the page on which given hypertarget is located. By default, hyperlink referencing hypertarget goes to the line of text where referenced hypertarget is located. However, instead I want it to go to the top of the page where this hypertarget is located, in similar way page \hyperlink{page.3}{page 3} does.

Here is MWE:

\documentclass{book}
\usepackage{lipsum}
\usepackage{hyperref}

\begin{document}

Following link will go to top of \hyperlink{page.3}{page 3}.

I want \hyperlink{mytarget1}{this link} to also go to top of page 3, because ``mytarget1'' is located on this page.

And \hyperlink{mytarget2}{this one} to top of page 4, because ``mytarget2'' is located on this page.

\lipsum[1-15]

\phantomsection\hypertarget{mytarget1}{mytarget1 is on this page}

\lipsum[5]

\phantomsection\hypertarget{mytarget2}{mytarget2 is on this page}

\end{document}

I found an answer to similar question, but question and answer deal with using \label as "target" destination.

This question is not a duplicate, because I want to achieve this with hypertargets, without need to use labels at all.

Is it possible?

Best Answer

I combined and \hypertarget and \label into one macro, using the same label name for the PDF link and the aux file \newlabel. One can use \hyperlink, \ref (which returns the \hypertarget text), \pageref and a new macro \pagelink (which links to the page anchor).

\documentclass{book}
\usepackage{lipsum}
\usepackage{hyperref}

\makeatletter
\newcommand{\pagetarget}[2]% #1=label (both hypertarget and label), #2=text
{\hypertarget{#1}{#2}\protected@write\@auxout{}{%
   \string\newlabel{#1}{{#2}{\thepage}{page.\thepage}{#1}{}}}}
\makeatother
% \hyperlink{#1}{button} will link to #2.
% \pagelink{#1}{button} will link to the page anchor.
% \ref{#1} will return #2 and link to #2.
% \pageref will return the page and link to #2.
% \getrefbykeydefault{#1}{name}{Doc-Start} returns the page anchor.

\newcommand{\pagelink}[2]% #1=label, #2=text
{\hyperlink{\getrefbykeydefault{#1}{name}{Doc-Start}}{#2}}

\begin{document}

Following link will go to top of \hyperlink{page.3}{page 3}.

I want \pagelink{mytarget1}{this link} to also go to top of page 3, because ``mytarget1'' is located on this page.

And \pagelink{mytarget2}{this one} to top of page 4, because ``mytarget2'' is located on this page.

\lipsum[1-15]

\pagetarget{mytarget1}{mytarget1} is on this page

\lipsum[5]

\pagetarget{mytarget2}{mytarget2} is on this page

\end{document}
Related Question