[Tex/LaTex] Tikz & Beamer: Change color “after pause”

beamertikz-pgf

I have a tikz drawing, where I want to change the color of the edge in the second slide. Right now I'm doing that in the brute force way of drawing a new edge in red over the previous one.

Is there any way that reduces redundancy in the code, and doesn't force me to redefine the whole arrow over and over? Something like \alert<2> in the standard beamer environment?

In particular, if on the third slide, I wanted the edge black again, I'd have to draw it a third time, black — that sounds suboptimal.

Current approach:

\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{positioning}

\tikzstyle{block} = [rectangle, draw, 
text width=6em, text centered, rounded corners, minimum height=3em]

\begin{document}

    \begin{frame}

    \begin{tikzpicture}
    \node [block] (I2) {I2};
    \node [block] [left=5cm of I2] (I1) {I1};

\path[->] (I1) edge[shorten >=0.5cm, shorten <= 0.5 cm] node [right, near start, align=center] {$q=1$\\$p=2$} (I2);

    \visible<2>{    \path[->] (I1) edge[shorten >=0.5cm, shorten <= 0.5 cm, color=red] node [right, near start, color=red, align=center] {$q=1$\\$p=2$} (I2);}


    \end{tikzpicture}

    \end{frame}
\end{document}

Best Answer

In this simple case, you could get away with just changing the colour using \only<2>{\color{red}}

\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{positioning}

\tikzset{block/.style={rectangle, draw, text width=6em, text centered, rounded corners, minimum height=3em}}

\begin{document}

    \begin{frame}

    \begin{tikzpicture}
    \node [block] (I2) {I2};
    \node [block] [left=5cm of I2] (I1) {I1};

    {\only<2>{\color{red}}\path[->] (I1) edge[shorten >=0.5cm, shorten <= 0.5 cm] node [right, near start, align=center] {$q=1$\\$p=2$} (I2);}

    \end{tikzpicture}

    \end{frame}
\end{document}

The clean and more flexible way would be to use the overlay-beamer-styles library. Then you could use alt=<2>{red}{black} to specify different colours.

\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{positioning}

\usetikzlibrary{overlay-beamer-styles}

\tikzset{block/.style={rectangle, draw, text width=6em, text centered, rounded corners, minimum height=3em}}

\begin{document}

    \begin{frame}

    \begin{tikzpicture}
    \node [block] (I2) {I2};
    \node [block] [left=5cm of I2] (I1) {I1};

    \path[->,alt=<2>{red}{black}] (I1) edge[shorten >=0.5cm, shorten <= 0.5 cm] node [right, near start, align=center] {$q=1$\\$p=2$} (I2);

    \end{tikzpicture}

    \end{frame}
\end{document}

enter image description here