Javascript onclick events failing to toggle video play/pause functionality

In my website, I have background music and a background video (webm format) embedded. I am facing an issue with making play/pause buttons in the form of png images work for both the video and the music.

The background music is added using the embed tag with id music:

<embed src="resources/bgsound.mp3" autostart="true" loop="true" hidden="true" id="music">

I prefer not to use the UI controls and want to stick with custom play/pause button images in .png format. The video is added as follows:

<video playsinline autoplay muted loop poster="resources/csgotrailer.png" id="bgvid">
<source src="resources/csgotrailer.webm" type="video/webm">
</video>

Below are the images intended to act as buttons:

<img src="images/play.png" alt="Play" height="30" width="30" id="play">
<img src="images/pause.png" alt="Pause" height="30" width="30" id="pause">

(each with their specific IDs). Here is the CSS styling for these images:

#play {
    position: fixed;
    top: 5%;
    left: 5%;
    opacity: 0.175;
}
#pause {
    position: fixed;
    top: 5%;
    left: 9%;
    opacity: 0.175;
}

The goal is to pause both the video and the music when clicking on #pause button, and resume playback when clicking on #play button. I have tried multiple JavaScript corrections but so far nothing seems to work:

var vid = document.getElementById("bgvid"),
pauseButton = document.getElementById("pause"),
playButton = document.getElementById("play"),
mus = document.getElementById("music");

playButton.addEventListener("click", function(event) {
    if (vid.paused == false && mus.paused == false)
        return;
    else {
        vid.play();
        mus.play();
    }
});

pauseButton.addEventListener("click", function(event) {
    if (vid.paused == true && mus.paused == true)
        return;
    else {
        vid.pause();
        mus.pause();
    }
});

No errors or warnings are showing up in the browser console, yet there is no response when clicking on the buttons. The script is linked in index.html as follows:

<script src="assets/js/buttons.js"></script>

The file is in the correct folder and all other scripts are functioning properly. Placing this script before others causes some of them to stop working and display errors. Any suggestions on what might be causing this issue?

Thank you for your help.

Answer №1

Through a process of trial and error, along with valuable input from @RoryMcCrossan, I successfully resolved the issue at hand. I made the decision to assign a z-index to the button IDs as it became evident that they were not functioning properly due to being obscured by other elements:

#play {
    position: fixed;
    top: 5%;
    left: 5%;
    opacity: 0.175;
    z-index: 1000;
}
#pause {
    position: fixed;
    top: 5%;
    left: 9%;
    opacity: 0.175;
    z-index: 1000;
}

This adjustment partially solved the issue. While the video could now be paused, the music continued playing without interruption. Upon further investigation, I discovered that the functions removeAttribute and stop() for the music were ineffective. It dawned on me that embeds do not possess the same attributes as background videos or audio files. Consequently, I made the decision to swap out the <embed> element for an <audio> tag:

<audio src="resources/bgsound.mp3" id="music" autoplay></audio>

By implementing this adjustment, all aspects of the functionality fell seamlessly into place. Both the pause and play buttons now operate flawlessly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refresh div content dynamically with anchor tag in place

I have a dilemma with the following div that contains an anchor tag linking to a php script responsible for updating information in a database and returning to this page. My goal is to execute this php script by clicking on the anchor tag, update the datab ...

Error: The function named 'setValues' has already been declared

Looking for some guidance with an error message that involves the 'setValues' declaration in my code. I've come across similar questions and answers, but I'm still unsure about what changes I need to make. Your input would be highly app ...

Error: An unexpected 'if' token was not caught

Encountering an error related to the question title while working with this code snippet: $LAB.queue(function setup() { FB.init({ appId: '00000000', status: true, cookie: true, xfbml: true, logging: &ap ...

Choosing options from an API response in a REACT-JS application

I have a Select Component in my application and I want it to automatically show the selected data once the response is received. import Select from "react-select"; <Select menuPlacement="auto" menuPosition="fixed" ...

How to Use Jquery to Select this Type of Identifier?

There is an identification like the following <input type="text" id=MyField[1d81c42a-4c8f-45a8-a219-0ff29d328103].Name /> In order for some Asp.net mvc code to function correctly upon submission and binding it to a model, this action needs ...

Encountering an error when attempting to parse a JSON Object in Java from an AJAX call

** Latest Code Update ** My JavaScript and Ajax Implementation: $(function() { $("#create_obd").bind("click", function(event) { var soNumber = []; $('#sales_order_lineItems input[type=checkbox]:checked').eac ...

Bootstrap Datatables for precise matches

Utilizing jquery bootstrap datatables for client-side data rendering with JSON as the data source, I have implemented a filter on top of the view/table using a combobox. The first column of the table contains values such as: Value A, Value AB, Value C, Va ...

Implementing a class change to anchor elements when rearranging them

I have 4 divs and their corresponding anchor tags. The active class is dynamically added to anchors on scroll unless the order of the display elements changes. In that case, active classes are only applied to the sorted elements. I also sorted the nav anch ...

By default, the HTML table will highlight the specific column based on the current month using either AngularJS or JavaScript upon loading

I am working with a table of 10 products and their monthly sales data. Using Angular JS, I am looking to highlight the entire column based on the current month and year. Additionally, we will also be incorporating future expected sales data into the table. ...

What is the best way to iterate through array elements with AngularJS?

I am looking to showcase array values using the ng-repeat directive, and then call the getimage function with itemid and photoidlist in order to retrieve the image URL. The JSON data that I have is as follows: $scope.productslist = { "json": { "re ...

Utilizing a hidden file-input, IE10 is able to transmit a FormData object via ajax

I'm encountering difficulties when trying to send a form that includes a display:none file-input via ajax. It works fine in Chrome (46.0.2490.71), but not in IE10 (10.0.9200.17492). I've tried various solutions without success, and it's cruc ...

I am currently working on adjusting the first two columns of the table, but I am encountering some issues with

I have successfully fixed the first 2 columns of a table, but now there is an extra row showing up in the table header. .headcol { position:absolute; width:7em; top:auto; left: 0px; } .headcol2 { position:absolute; width:15em; top:auto ...

Analyzing and sorting two sets of data in JavaScript

I am currently working with two arrays that are used to configure buttons. The first array dictates the number of buttons and their order: buttonGroups: [ 0, 2 ] The second array consists of objects that provide information about each button: buttons = ...

The CSS and Javascript files are failing to load

My web page is not displaying my CSS and JavaScript properly when I access it through a folder in the browser. Both files are located within multiple subfolders. I have attempted to rename the files to troubleshoot the issue. <head> <link rel=" ...

Pause a YouTube video automatically when the window is not in focus using FancyBox

I have successfully implemented dynamic play/pause functionality for a YouTube video, as demonstrated in my weave. However, I am facing challenges in making it work dynamically with FancyBox using the onBlur event (to pause the video when the window is no ...

Flexbox or Bootstrap 4 Grid: Which is the Better Choice?

My form is structured as follows: <div class="row"> <div class="col"> <textarea name="comment" class='form-control' placeholder='Type new comment here..'></textarea> </div> <div clas ...

The Ajax dropdown is failing to display any results

I created a script to filter through a database and retrieve all the records that contain a specific value. I have set up an AJAX dropdown for selecting the value, but when I make a selection in the dropdown, it does not show any results. Any assistance on ...

Concealing certain columns when the table exceeds a certain size

Hello everyone, I am just starting out in the world of React and web applications. Please feel free to reach out if anything is unclear to you. Here is the table structure that I currently have: <div> <table id="mytableid" className=&qu ...

Tips for incorporating validation/restrictions into react-datepicker

I've been working on implementing restriction and validation in a react-datepicker component. I'm utilizing redux-form for validation and normalization purposes. Issue: I've noticed that neither the normalizing function nor the validation f ...

What are the best methods for profiling a Node.js application at a specific point in its execution?

I am currently facing performance issues with my Node application, which listens to a websocket data feed and communicates with another API. The CPU usage is normally stable at around 2-5%, but occasionally (approximately 3 times within 24 hours) the incom ...