Having issues with ToggleClass and RemoveClass functionalities not functioning properly

As a novice in Jquery and CSS/scss, I've managed to create dynamic bootstrap cards for recording players. Each card consists of a music-container with control-play and vinyl elements. I aim to have multiple bootstrap cards generated based on the data in the DB. However, only one control-play should be active at any given time. This means that when one control-play is already playing and another is clicked, the previous one should stop, and its vinyl should revert back to the album cover. Essentially, only one record player with vinyl animation is allowed to play simultaneously. Unfortunately, the ToggleClass and removeClass methods are not working as expected. Additionally, there are instances where both control-play items trigger the click event even with a single click (I attempted using proxy to address this issue, but it proved ineffective).

Error: Upon running the fiddle, if I click on control-play1 for the first time, the vinyl of both music-player-containers is displayed instead of just the first one, and they are hidden only when control-play1 is clicked again. When clicking on the second control-play, it displays solely the second vinyl. Such behavior is unconventional.

JS


function MusicPlayer(mp, id) {
    this.mpc = mp;
    this.initEvents(id);
}

MusicPlayer.prototype = {
    initEvents: function(id) {
        var obj = this;
        obj.mpc.on('click', function(event) {
            var others = $("div.music-player-container").not($(this));
            $.each(others, function(index, value) {
                if ($(value).is('.is-playing .vinyl')) {
                    $(value).removeClass('is-playing');
                    $(value).addClass('is-not-playing');
                    $(value).toggleClass('is-not-playing', true);
                }
            });
            $(this).toggleClass('is-playing');
            event.stopPropagation();
        });
    }
}

$(function() {
    var $div = $('#content');
    $(".control-play").bind('click', $.proxy(function(event) {
        var cplay_clicked = $(event.target).attr('id');
        var $musiPlayerContainer = $div.find('#' + event.target.dataset.id + 'mpc');
        var mpc = new MusicPlayer($musiPlayerContainer, event.target.dataset.id);
        $('div.music-player-container').removeClass('is-playing');
    }, this));
});

CSS


/* Custom CSS */

[...]

HTML


<!-- Bootstrap cards -->

[...]

Visit JS Fiddle for full code

Creating an object of MusicPlayerContainer or utilizing bind() is crucial for proper functionality within the fiddle.


$(function() {
    var $div = $('#content');
    $(".control-play").on('click', function(event) {
        var cplay_clicked = $(event.target).attr('id');
        var $musiPlayerContainer = $div.find('#' + event.target.dataset.id + 'mpc');
        
        // Code for toggling between play states
        
        $('div.music-player-container').removeClass('is-playing');
    });
});

Answer №1

Upon reviewing your HTML code in the fiddle, I noticed that lines 24 to 28 are missing a closing tag for the </div> with the class 'music-player-container'. To rectify this, you should insert an additional </div> as shown below:

</div>
<!-2nd one->


<div class="music-player-container" id="2mpc">

Furthermore, there is also a missing </div> towards the end of the code snippet. You can refer to the corrected version here: https://jsfiddle.net/Twisty/ysLmyzb7/1/

In addition, my suggestion from earlier would be to consider utilizing the jQuery UI Widget Factory ($.widget()) for creating stateful jQuery plugins.

The jQuery UI Widget Factory allows you to create stateful jQuery plugins using the same abstraction as all jQuery UI widgets.

An illustrative example is provided below:

// Custom JavaScript code utilizing $.widget() for music player functionality /* Custom CSS styling for the music player */

You can explore this approach further through the recommended external fiddle link: https://jsfiddle.net/Twisty/ynmepyec/

Implementing the jQuery UI Widget Factory may require some additional effort, but it offers improved manageability and flexibility for your project.

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

How can we add styles to text entered into a form input field in a targeted way?

Is there a way to apply styling to the second word entered into a form input text field after the user hits "enter" and the data is output? In this scenario, the text always follows the format of 3 numbers, followed by a space, and then a name. For examp ...

Is it possible to directly add a child in HTML from nodejs?

I'm in the process of developing a chat application that requires users to select a room from a list of available rooms stored in <datalist> options, which are fetched from a SQL table on the server. Within my login.html file, users are prompte ...

I am unable to store a session variable using the GET method

Good day, I am seeking assistance with my code and have been searching for four hours without finding the error. I am working on an exchange where variables are stored in a session. The issue I am facing is that the variable $discount gets cleared every ti ...

Progressive Web App with Vue.js and WordPress Rest API integration

When creating an ecommerce website using Wordpress, I utilized Python for scraping data from other websites to compare prices and bulk upload products through a CSV file. My next goal is to learn Vue and transform the website into a PWA as it will be esse ...

Array data causes tabs to be shown incorrectly

My attempt to create tabs similar to those in this tutorial has hit a snag. While I can easily display hard coded tabs, I'm facing issues when trying to populate the tabs from a list as they end up being displayed incorrectly. Here is the code and im ...

Grabbing only the button element using jQuery when a click event occurs

HEY THERE! I have a simple question that I need help with. To better explain the issue, I've included a small code snippet below. The problem I'm facing is related to grabbing the id of a button. Everything works fine except when I click on any ...

Encountering a type error when making an Ajax request in JavaScript/jQuery

Encountering an error while trying to extract a value within a loop using jQuery. The error message is displayed below. Uncaught TypeError: Cannot read property 'no_of_optional' of undefined Below is the code I am working with. var data = $.pa ...

Implementing dynamic database content into a Wow Slider on a jQuery Mobile platform

I am currently using static data in a slider with wow slider jquery mobile. However, I would like to retrieve data from a database and display it in the slider. Can someone provide suggestions on how to do this? Thank you. <script type="text/javascri ...

How to style the first dropdown value in AngularJS to appear bold?

Is there a way to style only the first value in a dropdown list as bold without using jQuery? Here is the code for the dropdown: <div class="col-xs-3"> <select-box id="ad-version-select" options="curItem.stats.version" model="state.version" i ...

What is the best way to stop this Jquery slider from moving?

I've been struggling with this issue for what feels like forever, and it's driving me crazy! I have a slider on the homepage that I'm trying to enhance with a "click to pause" feature (and maybe even a click to resume, for good measure). I ...

What is the best way to transfer variables from an ng-template defined in the parent component to a child component or directive?

Is there a way to pass an ng-template and generate all its content to include variables used in interpolation? As I am still new to Angular, besides removing the HTML element, do I need to worry about removing anything else? At the end of this ...

Updating row values in an Angular table

I have a reusable table with the [cellData]="row" attribute to populate each cell on the table (see sample table in the screenshot). My question is, how can we replace the null values on the template with "---" so that instead of displ ...

Is there a way to prevent wrapping in a column, causing the last column to partially extend outside the container when the first column is hovered over?

Is there a way to prevent wrapping of a column so that when I hover over the first column, the last column displays half out of the container? I attempted to achieve this by setting the 25% to flex: 0 0 50%; in my column when hovering on the box-hover cla ...

Adding information to a designated included component (Angular)

I am trying to develop a directive for generating multiple choice activities. The concept is that within my scope, I hold a model containing an array of questions structured like this: function Controller($scope) { $scope.activity1 = { "questions" ...

Using Pug/Jade, be sure to call a function during each loop iteration

I'm attempting to develop a basic app, similar to a TO-DO LIST. I want to generate divs dynamically (with incremental ids) when a Button is clicked and then enter some text into an HTML input field. For example: <div id="item1"> <div id="ite ...

Ways to retrieve a list of identifiers from arrays at both initial and subsequent levels

I'm currently dealing with a JSON/JavaScript structure that looks like this: { "comments": [ { "id": 1, "content": "lorem ipsum", "answers": [] }, { "id" ...

Protractor: Saving data locally with local storage - A step-by-step guide

I've come across several instances of retrieving previously saved information, but I haven't found any examples of retrieving stored values. ...

What could be causing my Discord bot to remain offline even when I run the command node main.js?

After successfully installing node.js, I proceeded to type the command 'npm init' in the command prompt and then installed discord.js. However, upon installation of discord.js, a 'node_modules' folder was not added inside the project, w ...

Exploring the wonders of Lightbox when dealing with content loaded via AJAX

Using Bootstrap 5 along with the Lightbox library from , I encountered an issue. The Lightbox feature functions properly on regular page loads, but fails to load on content loaded via AJAX. I attempted to resolve this by implementing the following code: ...

Has the submit button become inactive once it has been inserted into a collapse?

I have recently implemented a collapse feature and inserted a form into it, but unfortunately, the submit buttons are not functioning properly. They are failing to send the data to the PHP file. <div class="container"> <div class= ...