Tips on utilizing toggleClass to display only the currently active item and obtaining the active class name

I am new to Jquery and CSS/scss and I have successfully created a dynamic boostrap card that resembles a record player. The goal is to generate multiple boostrap cards based on the data in DB, but for simplicity, I am showing only 2 examples below. My question is regarding how to manage the behavior of these record players - specifically, how do I ensure that only one player can be active at a time with vinyl animation? When a user clicks to play another card, the currently playing player should stop and revert back to the album cover using toggleclass. Please note that the code includes only the animation part and not the actual player functionality. How can I determine the current toggleclass name?


      <div class="container-fluid">
    <div id="content">
      <div class="music-player-container is-not-playing" id="1mpc">
        <div class="card card-inverse" id="1card">
          <div class="card-header" id="1cardHeader">
            <div class="top">
              <i id="1fav" class="favtoggle fa not-liked"></i>
              <i id="1pl" class="fa fa-plus-circle"></i>
            </div>
          </div>
...

javascript:

var $div = $('#content');
     var playButton = $('.control-play');
     playButton.on('click', function(e) {
       //alert(e.target.id);
       var $musiPlayerContainer = $div.find('#' + e.target.id + 'mpc');
       var $vinyl = $div.find('#' + e.target.id + 'vinyl');

       $(".music-player-container").not($('#' + e.target.id + 'mpc')).toggleClass('is-playing', false);
       $('#' + e.target.id + 'mpc').toggleClass('is-playing', true);
       e.stopPropagation();
     });

CSS

 
    /* Styles applied after bootstrap.css */

@import url(https://fonts.googleapis.com/css?family=Raleway:400,300,500);

/* More CSS styles... */ 

js-fiddle link:

Link to Code Here

Answer №1

There were a couple of issues with the fiddle code provided, which was preventing it from functioning correctly.

A. The jQuery URL linked in the code was incorrect, as it still contained ":" in the URL, causing it to fail to load properly. It is recommended to use the JavaScript Library directly from jsFiddle for future reference.

B. Loading JS before CSS, while not necessarily wrong, may be unhelpful in certain cases.

For a working example, please refer to: https://jsfiddle.net/Twisty/h72rxc32/

JavaScript

$(function() {
  var $div = $('#content');
  var playButtons = $('.control-play');
  playButtons.on('click', function(e) {
    var $musicPlayerContainer = $(this).closest(".music-player-container");
    var $vinyl = $musicPlayerContainer.find('.vinyl');
    console.log($musicPlayerContainer, $vinyl);
    $(".music-player-container").not($musicPlayerContainer).toggleClass('is-playing', false);
    $musicPlayerContainer.toggleClass('is-playing', true);
    e.stopPropagation();
  });

  $('[data-toggle="tooltip"]').tooltip()

  $('[data-toggle="popover"]').popover()
});

The code block should ideally be wrapped entirely. Using more precise selectors will enhance the readability and maintainability of the code in the future.

As mentioned earlier, the variable playButtons selects all buttons. Utilizing $(this) within the .on() method allows us to specify the target object clicked. Once the correct relationships are established, the remaining code functions as intended.

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

jquery line break in textarea

There is a 'edit description' button that, when clicked, makes text disappear and reappear if (id == 'commedit') jQuery(this).html('<textarea>'+jQuery(this).text()+'</textarea>'); else i ...

retrieve the current image source URL using JavaScript

In the template below, I am looking to extract the current img src URL and utilize it in a fancybox button. For example, in the template provided, there are 3 images from https://farm6.staticflickr.com. When clicking on these images, the fancybox will ope ...

What is the reason behind using AJAX to attempt sending a new URL request on

Having a strange issue with my product list. When trying to edit a product by clicking on it, I am redirected to the product form where an AJAX request is supposed to be sent to getFiltersGroup. However, on error, the AJAX request is somehow being sent to ...

Tips for inserting a button under a div when clicked

I am working on a layout where I have several div cards aligned side by side using the display: inline-block property. What I want to achieve is that when I click on a card, a button is added below the respective div. To accomplish this, I tried using jqu ...

Is it possible to implement a feature in Angular and Bootstrap where the toggle menu can be closed by clicking anywhere on the page, rather than just the toggle button

I'm working on an Angular project where I've implemented a navbar component. The navbar is responsive and includes a toggle button that appears when the browser window is resized. This button allows users to hide or display the menus. One issue ...

Creating a custom progress bar using Javascript and Jquery

I developed a progress bar that is fully functional. Here is the HTML structure: <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style ...

What is the best way to display grouped items horizontally in an ASP.NET ListView?

My ASP ListView currently displays items vertically in columns with GroupItemCount set to 3: A D G B E H C F I Is there a way to adjust the display so that it groups items horizontally in rows like this? A B C D E F G H I This is the ListVi ...

What is the best way to insert a row into a JavaScript table while incorporating a cell that utilizes the datepicker function in jQuery?

Currently, I am working on a javascript function: function addItem(tableID){ var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell1 = row.insertCell(0); var el ...

I am looking to create a feature for my table that adjusts its color scheme based on whether the number is odd or even

My current code is designed to change the background color of td elements for odd and even rows. However, when a new high score is entered, a new td is added but it does not get colored automatically as intended. I am facing an issue where the code is not ...

Display outcomes for chosen checkboxes

When I call the API: $url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order=' . $orderrecords[$k]["order_id"] . '&username=admin&password=admin123';, I retrieve the status results of all Order IDs and d ...

Chrome experiencing conflicts with backstretch when using multiple background images

In order to dynamically apply fullscreen background images in a WordPress site, I am utilizing Backstretch.js along with a custom field. Everything is functioning properly for the body's background image. However, there seems to be an issue with anot ...

Every fourth list item, beginning with a designated number

I'm attempting to add a border to specific list items in my HTML. I want the border to start from the 9th child and then continue every 4th child after that. For clarification, I'd like the 9th, 13th, 17th, 21st, 25th... list items to have white ...

The Date Picker pops up automatically upon opening the page but this feature is only available on IE10

There seems to be an issue with the date picker opening automatically on IE10, while it works fine in Firefox where it only appears when you click on the associated text box. Does anyone have insight into why this might be happening specifically in IE10? ...

Secret icon revealing on mouseover

I devised a simple technique to showcase an element overlapping another, like an overlay, and it was functioning flawlessly until the point where I needed to incorporate a "button" (styled as a Bootstrap anchor) beneath it. Here is the initial setup and h ...

How to retrieve plain text data from a jQuery ajax call to a PHP server

Having trouble getting my ajax request to a php page to return plain text. Here's the code snippet: $.ajax({ type: 'GET', url: '/shipping/test.php', cache: false, dataType: 'text', ...

Calculating the total number of clicks on a button using PHP

I am attempting to track the total number of clicks on a button by individual users, rather than combining all members' clicks. Each user's clicks on the button should be logged separately. I am struggling to determine the best approach for this ...

Determining outcomes of forms added in real-time

Need assistance with dynamically creating tickets, calculating prices, and displaying results when additional tickets are added. Currently facing an issue where price data is not being calculated when a new ticket is added. Any help would be greatly apprec ...

Can you guide me on where to find the login with Facebook button on this site?

I am currently working on integrating a Facebook authentication system into my app, but I find the default log in button provided by Facebook developers section to be quite unappealing. My Question: I am curious about how websites like Stack Overflow man ...

Utilize a Material UI GridList to transform images into a captivating background display

Incorporating a GridList displaying a variety of images fetched from an external source, I have successfully created an ever-changing image gallery. Now, my goal is to convert this dynamic image gallery into grayscale or transparency and utilize it as a ba ...

What is the best way to address background-image overflow on a webpage?

I'm facing a challenge in removing the overflow from a background-image within a div. There are 4 divs with similar images that combine to form one background image (I adjust the position of each image so they align across the 4 divs). Essentially, I ...