Add code to switch the image when the music is being played

I have a scenario where I am using this code to control the playback of song samples, and there are multiple instances of it on the page. I am looking to enhance this functionality by adding some code that will change the background-image of only the specific instance with the .playback class to pausebutton.gif after the song is played. Furthermore, when the button is pressed again, I want it to change back to playbutton.gif. Since there are multiple instances on the page, I am wondering if this can be achieved using a class. Any assistance on how to implement this would be greatly appreciated. Thank you.

<script type="text/javascript>
$(function() {
$(".playback").click(function(e) {
   e.preventDefault();
   var song = $(this).next('audio').get(0);
   if (song.paused)
     song.play()
   else
     song.pause()
   });
   });

<style>
.playback:link   
{background:url('images/playbutton.gif');display:block;width:18px;height:18px;}
</style>

<a class="playback" href="#"></a><audio id="wonderful"><source src="audio/wonderful.mp3" type="audio/mpeg"  /></audio>

Answer №1

To enhance your CSS, you can include the following code:

.playback.playing {
    background: url('images/pausebutton.gif');
 }

This particular style will target elements that have both the classes playback and playing.

Then, in your JavaScript:

$(".playback").click(function(e) {
    e.preventDefault();
    var song = $(this).next('audio').get(0);
    if (song.paused) {
        song.play();
        $(this).addClass("playing");
    } else {
        song.pause();
        $(this).removeClass("playing");
    }
});

When the click event occurs, the reference to $(this) within the function isolates the specific element with the class playback that was clicked. The addClass method then adds the playing class solely to the link associated with the played song. To further explain, I utilized removeClass to eliminate the playing class when the song is paused.

If feasible, a more efficient approach would involve merging playbutton.gif and pausebutton.gif into a single 36x18 image named playbackbuttons.gif. Adjust your CSS as follows:

.playback:link {
    background: url('images/playbackbuttons.gif');
    display: block;
    width: 18px;
    height: 18px;
}

.playback.playing {
    background-position: right top;
}

(The JavaScript code remains unchanged from my previous explanation.)

With this modification, the pause button image loads upon the initial page load rather than when a song begins playing for the first time.

Answer №2

e will represent the jQuery.Event object, so be sure to utilize $(this):

$(".playback").click(function(e) {
    e.preventDefault();
    var track = $(this).next('audio').get(0);
    if (track.paused) {
        track.play();
        $(this).addClass("playing");
    } else {
        track.pause();
        $(this).removeClass("playing");
    }
});

I showcased using color in my example, but remember to modify it to use background-image instead.

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

Why do images not show up when they are in the same directory in HTML?

article.uk{ background-image: url("GB_Flag.jpg"); background-color: #95a5a6; background-repeat: no-repeat; background-position: right top; width: 75%; background-size: contain; color:#d98880; } <a href="GB.html" target="Great_Britain_Page"> < ...

Export data from jQuery DataTables to Excel file

Trying to export the datatable (example) into Excel or CSV using TableTools, but the icons (export/print/csv/...) are not showing up with the code provided. Have made several changes but nothing seems to work. What am I missing? Is there an implementation ...

What is the best way to ensure that my text is perfectly centered both horizontally and vertically within this DIV?

What's the best way to vertically and horizontally center text? Here is an example code that needs to be centered: <div style="display: block; height: 25px;"> <span id="ctl_txt" style="background-color: rgb(255, 0, 0);"> Basic ...

Creating a Dynamic Division Using jQuery

I'm new to jQuery and I need help creating individual divs and submit buttons with unique names for each one. Can someone assist me? $(document).ready( function() { init(); }); function init() { setTimeout( function() { fetchUpdate ...

Displaying and Concealing Elements with AngularJS and Implementing Alternating Styles

Within my collection of div elements showcasing product information, there is a need to display or hide specific fields based on the product type. While this functionality works smoothly, we now aim to enhance readability by implementing alternating row st ...

Deciding Between Javascript DOM and Canvas for Mobile Game Development

My idea for a mobile game involves using the Phonegap framework to create a game where players can control a ball's movement by utilizing their phone's accelerometer. I also envision incorporating other elements like enemies and walls into the ga ...

Discover the best method for combining and comparing arrays using jQuery

Currently, I have two arrays: existing_names = username1, username2, username3; new_names = username1, username4, username5; I want my final array to be like this: final_names = username1, username2, username3, username4, username5; Is there a way to ...

Visualizing live data streaming from MySQL

I am currently using this code to retrieve values from a database and create a basic line graph (showing response time to an alert vs. UTC time). Everything works smoothly when the data is static, but now I want to try retrieving the data in "real-time" (j ...

Interactive front end design for decision trees

On the front end, I aim to enable users to influence the outcome of a Decision Tree based on their selections. For my Django-React App, I have adopted the style and tree example from the codeplayer. You can find it here: I am tasked with creating an unor ...

Changing the position of an element in CSS using the center as the reference point, based on a JavaScript variable: How can it be done?

I have an image marking a scale, with the marker's position in HTML set as: <image class="red-marker" xlink:href="./assets/images/marker.png" [attr.x]=percentage width="12" height="40" y="0" ></image> But I want the middle of the marker ...

Utilizing document.getElementById to toggle the CSS to 'display:none'

Attempting to modify the CSS property using document.getElementById, I wrote the following code: var x = document.getElementById("id"); x.style.display = "none"; Unfortunately, this code is not functioning as expected. Can someone pr ...

"Utilizing Bootstrap to add borders to div elements is a

https://i.sstatic.net/yPt46.png Hey there! I am working on a project using bootstrap 4. I encountered an issue that I can't seem to solve. I placed an image inside a div, set the div's height and width to 200px with overflow hidden. The image w ...

Unable to adjust the dimensions of a Mailchimp input field

Having some trouble customizing my Mailchimp form a bit and could use some assistance. Snippet of the code: <!-- Begin MailChimp Signup Form --> <link href="//cdn-images.mailchimp.com/embedcode/horizontal-slim-10_7.css" rel="stylesheet" type=" ...

The controller argument for Ajax data object is found to be empty

Currently, I am attempting to make an ajax call to a controller method that accepts an object. The code I have at the moment is as follows: [HttpPost] public ActionResult EditStudent(Student student) { //do something } Here is the Ajax call I am us ...

Retrieving JSON information from a RESTful API

I am facing an issue with a REST service that I have set up to return sample JSON data: public string DoJSONWork() { return "{\"name\":\"unknown\", \"age\":-1}"; } My intention is to consume this service fr ...

Storing newly generated rows using PHP and JavaScript

In my form, I have dynamically added rows that work properly. Once the user fills in the form fields and clicks on the "check correctness" submit button, validation is performed. If the data is incorrect, a correction is required. If the data is correct, a ...

Choose a portion of the content within a div element

In my SVG element, I have created a foreignObject with a textarea and a div inside. The textarea is transparent and lies on top of the div. As users type in the textarea, the text gets copied to the div creating a WYSIWYG editor. Everything functions corre ...

Tips for displaying a message if an Ajax function returns zero records

Looking for a way to display the message "No data to display" when the JSON response from an Ajax call is 0 in a DataTable, but running into difficulties figuring out how to do so. Attempted: $("#noData").show(); using an if statement, however, it did no ...

Choose a particular element using a randomly generated ID in JQuery

One challenge I am facing is that the ID of an element is generated randomly: <?php echo "<input id='input'".uniqid()." />"?> I'm wondering how to access this element using jQuery. Is it possible to access it using a wildcard l ...

Error: Page not found - The requested URL localhost:8080/login could not be located

My first time trying to utilize ajax and json is resulting in a 404 error. The issue seems to be that /login cannot be found even though I have defined LoginServlet with the url pattern /login in web.xml. Here is the code from web.xml: <servlet> ...