Toggle button for timeline play / reverse

Hi, I'm trying to create a button that:

  1. on click, starts a timeline, adds class "clicked"
  2. on second click, reverses the timeline, and removes the class "clicked", thereby restores original button label and color.

I can get Step 1 working, but on second click, it just restarts the timeline.

I looked at this earlier thread as a reference, but was not able to use it to solve my problem: Toggle animation Play / Pause

Here's my code:

// Function: Check if class "clicked" exists, and if it does, reverse the timeline

	var button = hypeDocument.getElementById('clickHere');
	if (button.classList.contains('clicked')) {
		button.classList.remove('clicked');
		button.innerHTML = "Click Here";
		hypeDocument.continueTimelineNamed('box opens', hypeDocument.kDirectionReverse, false)
	}

This is the function that starts the timeline, which works:

// Start Timeline on click
	var button = hypeDocument.getElementById('clickHere');
		button.innerHTML = "Reverse Timeline";
		button.classList.add('clicked');
		
	hypeDocument.startTimelineNamed('box opens', hypeDocument.kDirectionForward);

Here's a video of what happens:

And here's my Hype file:
toggle-timeline-play-reverse.hype.zip (18.4 KB)

Any help is appreciated. Thanks!

Since you're always calling the function startOrReverseTimeline as the second function on click, it always gets executed – regardless of whether the class clicked is present or not. Instead, use this function in an else statement inside checkClicked.

var button = hypeDocument.getElementById('clickHere');
	
	if (button.classList.contains('clicked')) {
		console.log('true');
		button.classList.remove('clicked');
		button.innerHTML = "Click Here";
		hypeDocument.continueTimelineNamed('box opens', hypeDocument.kDirectionReverse, false)
	
	} else {
	
		button.innerHTML = "Reverse Timeline";
		button.classList.add('clicked');
		
		hypeDocument.startTimelineNamed('box opens',  hypeDocument.kDirectionForward);
	}

toggle-timeline-play-reverse_kt.hype.zip (16.2 KB)

3 Likes

One could also compare duration to current time and determine if the player is at the end that would be open and otherwise closed and determined the plate direction

1 Like

Thanks very much @ktewes , this works! Combining the conditions into a single function does the trick.