Reputation: 13
(BRAND new to javascript) I have created a simple play/pause button but will only work on desktop. Can i make a simple alteration to code to make the button work on mobile?
I have tried to swap out the .onclick event with .ontouchstart but it will not work on iphone
<script>
var video = document.querySelector('.video');
var btn = document.getElementById('play-pause');
function togglePlayPause() {
if(video.paused) {
btn.className = "pauseButton";
video.play();
}
else {
btn.className = "playButton";
video.pause();
}
}
btn.onclick = function() {
togglePlayPause ();
};
</script>
I expect the video to pause but does nothing when clicking on mobile
Upvotes: 1
Views: 1292
Reputation: 96
Try registering an event listener to the button according to the touch support:
// Check touch support
let touchEvent = 'ontouchstart' in window ? 'touchstart' : 'click';
var video = document.querySelector('.video');
var btn = document.getElementById('play-pause');
function togglePlayPause() {
if(video.paused) {
btn.className = "pauseButton";
video.play();
} else {
btn.className = "playButton";
video.pause();
}
}
// Bind event
btn.addEventListener(touchEvent, togglePlayPause);
Update
I've put my snippet in your code
Upvotes: 3