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

Issue encountered: Next.js has failed to hydrate properly due to a discrepancy between the initial UI and server-rendered content

Uncertain about the cause of this error? The error seems to disappear when I remove the provided code segment. What is triggering this error in the code snippet and how can it be fixed? <div className="relative flex flex-col items-center pt-[85.2 ...

Testing with mount in React Enzyme, the setState method does not function correctly

I've been experimenting with testing this code block in my React App using Jest and Enzyme: openDeleteUserModal = ({ row }: { row: IUser | null }): any => ( event: React.SyntheticEvent ): void => { if (event) event.preventDefault(); ...

Issue with PHP incorrectly encoding JSON when writing to a file

I encountered a problem while working on this task. I used preg_split in PHP to create an array. However, my challenge now is converting it into JSON format. Despite trying several methods, the resulting code appears poorly written and does not seem to be ...

Using react-big-calendar exclusively for the month view

I need help customizing react-big-calendar to only show the month view and trigger a function when a date is selected. I want to remove all other functionalities related to week, day, agenda, and time display. Essentially, I just want to display the month- ...

Troubleshooting problem with Zscaler and Ajax communication

When making an AJAX call on my website, everything runs smoothly except for when it is accessed behind a Zscaler proxy. In that case, the browser throws a CORS error: "No 'Access-Control-Allow-Origin' header is present on the requested resource. ...

The state variable remains undefined even after integrating useEffect in a React.js component

Hello, I have a component within my React application that looks like this: import React, { useEffect, useState } from "react"; import AsyncSelect from "react-select/async"; import { ColourOption, colourOptions } from "./docs/data"; const App = () => ...

Is there a way to automate the duplication/copying of files using JavaScript?

I have a GIF file stored in the "assets" directory on my computer. I want to create multiple duplicates of this file within the same directory, each with a unique filename. For example: If there is a GIF file named "0.gif" in the assets directory, I woul ...

How to Route in Angular 5 and Pass a String as a Parameter in the URL

I am currently working on an Angular project that focuses on geographic system data. The concept is as follows: I have a component with the route: {path: 'home'}. I aim to pass a geojson URL along with this route, making it look like this: {pat ...

The json encoding process results in a non-JSON entity

Utilizing $.ajax to validate data in my controller has been successful, except when there are processes preceding the variables that are placed into an array for json encoding. Despite the controller echoing the data, the view fails to render it as json en ...

What is the best way to intelligently cache specific segments of a page in PHP?

Issue: I am working on a website with over 50,000 pages, the majority of which are only updated once at the time of creation. I am in the process of implementing caching for these pages since they do not require frequent content changes. However, I am fa ...

Do external JavaScript files exclusively serve as repositories for functions?

Hey there, I'm a beginner in Web Development and I have a question that might sound silly: If I decide to keep my scripts in an external .js file, would it essentially just serve as a container for functions? For instance, if I attempt to include cod ...

What is the maximum character limit for the JQuery validation plugin?

Currently, I am utilizing the JQuery validation plugin in my project. My goal is to set a maxlength for one of the fields. Here's an example of how it can be done by defining rules externally: rules: { Message: { required: false, maxLe ...

The browser does not support the display of Spanish special characters

I am working on a website and need to incorporate support for the Spanish language. I have prepared an XML file with both English and Spanish text. The XML file is being read based on the user's selection of language from a dropdown menu. Everything s ...

Differences in outcomes have been observed between the elementLocated and findElements functions

Currently, I am in the process of developing Webdriver automation for a specific web application. As part of this process, I have created a test that seems to be functioning well most of the time but occasionally encounters an issue. it('verifies pre ...

Arrange a pair of div containers side by side on the webpage without the need to alter the existing

Is there a way to align these two div side by side? <div class="main_one"> <div class="number_one">Title A</div> </div> <div class="main_two"> <div class="number_two">Title B</div> </div> <div class=" ...

Navigating and extracting nested JSON properties using JavaScript (React)

I am currently working with a nested JSON file that is being fetched through an API. The structure of the JSON file looks something like this: { "trees":{ "name":"a", "age":"9", "h ...

SinonJS - Retrieving Property Value Prior to Stub Invocation

Currently leveraging sinon.js for stubbing functionalities where it is feasible to stub and spy on methods but not properties based on my observations. I'm interested in knowing if there's a way to verify whether state.searchText gets assigned t ...

Two shapes engaging in mutual interaction

I am faced with a situation where I have two identical forms on different pages. Page 1 The form on this page serves as a quick call to action, pre-populating the form on the next page. <form action="/xxxx" method="post"> <select id="islan ...

JavaScript post method for JSON data: no input or output values

I am currently developing a page that extracts data from an HTML table consisting of two columns and an index of a form, and then converts it into a JSON string. The intention is to pass this data into PHP for further processing, perform calculations on th ...

The html.dropdown feature is not maintaining the selected value chosen

After successfully filling out my form and submitting data to the database, I encountered a problem with the drop downs on the form not showing the selected value if the model fails validation. Although the HTML clearly shows that the value of the dropdow ...