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

Incorporate a background image with the JavaScript CSS property

I'm having trouble adding a background image using the Javascript CSS property in my code. When I directly add the 'url', it works fine. Could the issue be with the 'weatherImage' variable? Javascript var OpenWeatherKey = ' ...

Create a customized HTML popup featuring various packages

I am struggling to create an HTML popup within a React component due to some errors Here is the code snippet: <div> <button class="toggle">Button</button> <div id="link-box"> <ul> ...

Navigate through the options on the left menu by sliding your

I'm attempting to create a menu that slides in a submenu from the left on hover, but the issue is that with this code, all submenus open instead of just the one related to the hovered link. Here is my HTML code: <ul id="NavMenu"> ...

Building interactive web forms with real-time validation using CodeIgniter

I'm looking for a way to use ajax (jquery library) to validate my forms. Specifically, I have a form that requires a minimum password length of 6 characters. Currently, I have implemented the validation rule as follows, $this->form_validation-> ...

Enhancing jQuery Mobile listview with voting buttons on each item row

I am looking to incorporate 2 vote buttons within a jQuery mobile listview, positioned on the left-hand side and centered within each list item. While I have managed to achieve this using javascript, my goal is to accomplish it without any additional scrip ...

Tips for setting up a range slider for decimal numbers

I have implemented the following code for a range slider. It works perfectly fine for integer values like 1 and 100, but I am facing issues when trying to use decimal values. I attempted to substitute 1 with 0.1 but it did not yield the desired result. ...

What is the method to retrieve a checkbox value within a datatable when employing pagination?

I recently came across an issue with my datatable where I had implemented a checkbox in the first column of each row. However, when I attempted to check the checkbox using an AJAX call, it only worked for the first page and not for any subsequent pages. H ...

Issue with triggering the change event for <select> tag

Whenever the selected value of the drop down changes, the following code does not work as expected. Please make corrections if any errors are present. <!doctype html> <html lang="en"> <head> <meta charset="utf-8</scri ...

Problem with maintaining the alternating background color of table rows while using jQuery's animate() function

I have an HTML table that I styled with alternating row background colors. <table class="tb_record"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> < ...

Stop users from signing up if the chosen username is already in use

I have a script that successfully checks if a username is available, but even if the username is already taken, the user can still register. I am looking for a way to prevent registration if the username is not free. Here is the code snippet: index.php $ ...

Why are the variables not reflecting the changes when an event is triggered?

I'm a beginner in programming and would really appreciate some guidance. Why are my variables not updating when I click the button?? Here is the HTML code snippet: <h1>NIM</h1> <p>Welcome to a simple edition of the game NIM</p& ...

What is the reason why the show() function in JQuery only applies to one specific element, rather than all elements selected with the same selector?

JSFiddle. This example code features a nested <table> within another <table>. The main issue concerns the click listener for the #add button. Specifically, the final if/else statement in the function. When you execute this code and click the ...

The CSS code seems to be ineffective when attempting to center elements with a specific width in react.js

Hey everyone, I'm currently working on developing a web application using react-bootstrap and I've encountered an issue with adjusting the width of my row and centering it. I have already created the necessary CSS and JS files, but I am unable to ...

Design a layout featuring an array of boxes in varied sizes

Is it possible to create a grid layout with 3 columns containing div boxes of varying heights, all populated with content extracted from a database? ...

Echo command fails to work with location.href

I am facing a small issue with my PHP echo. I have a JavaScript link function that is not working because the HTML code shows this type of link onclick="location.href="http://www.link.com/";". It's clear that this syntax won't work. However, if w ...

The issue of not being able to type in the sweetalert 2 input within a material UI modal in a

Within a card displaying an order, there is a sweetalert2 popup that opens when trying to cancel the order, asking for a cancellation reason. This feature works seamlessly on the orders screen. <Grid item md={8} sm={12}> orders.map((order) => ...

Adjust the left and right margins while maintaining the vertical margin spacing

Is there a way to apply horizontal margin while inheriting vertical margin without explicitly setting margin-left and margin-right? I was hoping for something like margin: inherit 20px; to be effective. Take a look at the example here: https://jsfiddle.ne ...

Modify the contents of the 'data-content' area in the popover

Looking for a solution where I can update only a portion of the data-content within a popover. Here is an example code snippet: <div class="popover-wrapper"> <i class="glyphicon glyphicon-question-sign hover_content" ...

Mysterious and never-ending loop that seems to loop endlessly and eludes my

My prototype includes a method for adding callbacks: /* * Add a callback function that is invoked on every element submitted and must return a data object. * May be used as well for transmitting static data. * * The callback function is supposed to e ...

retrieving embedded content from an iframe on Internet Explorer version 7

Need help with iframe content retrieval $('.theiframe').load(function(){ var content = $(this.contentDocument).find('pre').html(); } I'm facing an issue where the iframe content is retrieved properly in FF, Chrome, and IE 8,9 ...