Prevent sound from continuing to play when a different DIV is selected

I require help in developing a compact soundboard for my project to deepen my understanding of jQuery. The objective is to halt and reset the audio from the current file when another div is clicked, prompting the playback of its corresponding audio file instead. Here's how my page is currently laid out:

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Parisienne" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Archivo+Narrow" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet" type="text/css" />
  <script type="text/javascript" src="js/jquery.js"></script>
  <script type="text/javascript" src="js/jquery-ui.js"></script>
  <script type="text/javascript" src="js/playaudio.js"></script>
    <title>Sample</title>
  </head>
  <body>
      <div class="title">Sample</div>
      <div id="accordion">
  <h3 class="accordion-title">Who Are We?</h3>
  <div class="accordion-content">
    <p>
    Content
    </p>
  </div>
  </div>
        <div class="wrapper">
          <div class="shake-overflow">
            <div id="button-div1"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Did He Really?</p></div>
            <div id="button-div2"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Train Tracks</p></div>
            <div id="button-div3"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Ayyy</p></div>
            <div id="button-div4"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Petey</p></div>
          </div>
          <div class="shake-overflow">
            <div id="button-div5"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Mr. Raj</p></div>
            <div id="button-div6"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Mary</p></div>
            <div id="button-div7"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">At The Port</p></div>
            <div id="button-div8"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Twister</p></div>
          </div>
          <div class="shake-overflow">
            <div id="button-div9"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Lewis Poois</p></div>
            <div id="button-div10"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">You're a Prick!</p></div>
            <div id="button-div11"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">AHAHAHA</p></div>
            <div id="button-div12"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">I Lived There</p></div>
          </div>
        </div>
  </body>
</html>

CSS:

body{
  background: url(../img/leather-jacket.jpg) 50% 0 no-repeat fixed;
  background-size:cover;
  overflow: scroll;
  overflow-x: hidden;
}

img{
  max-width: 100%;
  height:auto;
}

.ui-state-focus { outline: none; }

.accordion-title{
  text-align: center;
  color:white;
  font-family: 'Parisienne', cursive;
  font-weight:normal;
  font-size: 30pt;
  width: 30%;
  margin: 0 auto;

}
...</questionbody>
<exquestionbody>
<div class="question">
                
<p>I was wondering if you could help me create a small soundboard for a project that will help me understand jQuery better. My goal is to stop the audio from the current file and play the associated audio file when another div is clicked. This is how my page is set up at the moment:</p>

<p><strong>HTML:</strong></p>

<pre><code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Parisienne" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Archivo+Narrow" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet" type="text/css" />
  <script type="text/javascript" src="js/jquery.js"></script>
  <script type="text/javascript" src="js/jquery-ui.js"></script>
  <script type="text/javascript" src="js/playaudio.js"></script>
    <title>Sample</title>
  </head>
  <body>
      <div class="title">Sample</div>
      <div id="accordion">
  <h3 class="accordion-title">Who Are We?</h3>
  <div class="accordion-content">
    <p>
    Content
    </p>
  </div>
  </div>
        <div class="wrapper">
          <div class="shake-overflow">
            <div id="button-div1"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Did He Really?</p></div>
            <div id="button-div2"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Train Tracks</p></div>
            <div id="button-div3"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Ayyy</p></div>
            <div id="button-div4"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Petey</p></div>
          </div>
          <div class="shake-overflow">
            <div id="button-div5"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Mr. Raj</p></div>
            <div id="button-div6"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Mary</p></div>
            <div id="button-div7"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">At The Port</p></div>
            <div id="button-div8"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Twister</p></div>
          </div>
          <div class="shake-overflow">
            <div id="button-div9"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">Lewis Poois</p></div>
            <div id="button-div10"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">You're a Prick!</p></div>
            <div id="button-div11"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">AHAHAHA</p></div>
            <div id="button-div12"><img id="mobile-img" src="img/ralph-tongue.png" /><p class="button-text">I Lived There</p></div>
          </div>
        </div>
  </body>
</html>

CSS:

body{
  background: url(../img/leather-jacket.jpg) 50% 0 no-repeat fixed;
  background-size:cover;
  overflow: scroll;
  overflow-x: hidden;
}

img{
  max-width: 100%;
  height:auto;
}

.ui-state-focus { outline: none; }

.accordion-title{
  text-align: center;
  color:white;
  font-family: 'Parisienne', cursive;
  font-weight:normal;
  font-size: 30pt;
  width: 30%;
  margin: 0 auto;

}

.accordion-title:hover {
  cursor: pointer;
}

.accordion-content{
    margin:0 auto;
    margin-top:2%;
    margin-bottom:2%;
    background: rgba(0, 0, 0, 0.25);
    border: 1px solid rgba(255,255,255,.22);
    width:40%;
    padding:15px;
    color:white;
    font-family: 'Archivo Narrow', sans-serif;
    font-size: 15pt;
}

.accordion-content p {
  -webkit-margin-before: 0em !important;
  -webkit-margin-after: 0em !important;
  text-align: justify;
}

.title{
  font-family: 'Parisienne', cursive;
  font-size: 50pt;
  font-weight:normal;
  text-align: center;
  color:white;
  border-bottom: 1px solid rgba(255, 255, 255, 0.29);
  margin-bottom:3%;
}

.wrapper{
  width:80%;
  background: rgba(0, 0, 0, 0.25);
  margin:0 auto;
  border:1px solid rgba(255,255,255,.22);
  overflow: hidden;
  padding:2%;
  margin-top:2.5%;
}

.wrapper img{
  margin-top:1%;
}

.logo{
  height:auto;
}

.shake-overflow{
  overflow: hidden;
}

.button-text{
  margin:1% 0 1% 0;
}

/*4 Column*/

#button-div1{
  width:20%;
  float:left;
  margin-right:6.53%;
  border:1px solid rgba(255,255,255,.22);
  margin-bottom:2%;
  font-family: 'Archivo Narrow', sans-serif;
  font-size:20pt;
  color:white;
  text-align: center;
}

#button-div1:hover{
  cursor:pointer;
  background: rgba(54, 54, 54, 0.28);
}

#button-div2{
...
 
 ...
    
  });

});

Currently, I am defining variables to store audio elements and playing them on click events of specific divs. To improve this, you can refactor the code to eliminate repetition by assigning a common class to all button divs and using a mapping approach to handle the click events more efficiently. This way, you can enhance the readability and maintainability of your code.

I hope this solution helps you in achieving your desired functionality effectively.

Answer №1

Eliminating redundancy in your code is a crucial step towards improvement. One way to achieve this is by refactoring the code to include a common class for all button divs, such as "button-div". By doing so, you can replace the individual click event handlers on each div with a unified function like the one below:

var divAudiosMap = {"button-div1": reallyObj, "button-div2": trainObj, ...};

$('.button-div').click(function() {
    var divID = $(this).attr('id');
    divAudiosMap[divID].play();
});

Utilizing a map in this manner not only reduces repetition but also simplifies the code structure, making it easier to manage without relying on multiple if statements.

I trust that these suggestions will prove beneficial to your project. Feel free to reach out if you have any further questions.

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

PHP is receiving data from $.post in an invalid format

I am facing a challenge in sending a JavaScript Object() to a PHP file in the correct format that $.POST requires. The PHP file does not establish any $_POST[] variables, which suggests that I may be transmitting the data in an improper format. JS: $(&ap ...

Fade in images using jQuery

I am having issues with fading in and out images using jQuery, it doesn't seem to be working as expected. I think there might be something crucial that I am missing. Take a look at the script below: var count = 1; setInterval(function() { ...

Is there a way to achieve a transparent background while animating the second text?

I am seeking to create a unique typography animation that involves animating the second text, which is colored and consists of multiple text elements to animate. The animation should showcase each text element appearing and disappearing one after the other ...

Combining strings within a string after a specific word with nested Concatenation

In a given string variable "str," I am looking to concatenate another string between "InsertAfterMe" and "InsertBeforeMe". str="This is a string InsertAfterMe InsertBeforeMe" s1="sometext" s2="soMoreText" aList=[1,2,3,4,5] The concatenated string shoul ...

Is there a way to extract information from the HTML source code of an external website and display it in my application?

Seeking a method to search an external URL for content that matches "title" and then display the results on my HTML page using Javascript. Despite my efforts with Javascript, I have not come across any resources that address this issue. Could it be that I ...

What sets $(document).on apart from ($ document).on in CoffeeScript?

One of my buddies is incorporating ($ document).on into his CoffeeScript script. I'm curious to know if this differs from the typical $(document).on and, if it does, how so? ...

Icons will be displayed when hovered over

Is it possible to display icons on hover in a div and hide them otherwise using just CSS? Or do I need to use javascript for this function? Thanks in advance! Example: HTML: <div id="text_entry"> <p>Some text here</p> <span ...

Retrieve a collection of CSS classes from a StyleSheet by utilizing javascript/jQuery

Similar Question: Is there a way to determine if a CSS class exists using Javascript? I'm wondering if it's possible to check for the presence of a class called 'some-class-name' in CSS. For instance, consider this CSS snippet: & ...

Display a textarea field on the current page using AJAX technology

My goal is to display the value of a textarea input in real-time by utilizing the keyup event in my showContent div. However, I lack expertise in Ajax and/or JQuery and would appreciate some assistance. The form located in formPage.phtml (I'm unsure ...

Create a dynamic feature that allows users to easily add text fields within a form in

I'm looking to create a form that adds another input text field automatically when the user fills out one. Here is an example of the HTML structure: <form method="post" action="http://localhost/save" class="save"> <fieldset> <div&g ...

Improving Page Load Speed with HTML Caching: Strategies for Enhancing Performance when over half of the data transferred is for navigation menus

I manage a complex and expansive website that contains a significant amount of repetitive HTML elements such as the navigation menu and top ribbon. Loading a single page on my site can be resource-intensive, with up to 300KB of data required, half of whic ...

The selection feature is not supported for the type of input element in jQuery

I'm currently attempting to utilize AJAX to send a form with jQuery. However, upon clicking the submit button (which is technically a link), I encountered an error. The error displayed in the console is as follows: Failed to read the 'selection ...

Tips on how to navigate to the end of a div that has been created through ng-repeat in Angular JS with the

Here is the template code I am working with: <div class="chatbox" id="mailBody" > <div class="panel-body" ng-repeat="mail in mails"> <div class="m-b-none" ng-if="mail.inboxMessageType == 1"> <a href class="pull-left ...

Trouble with Woocommerce Checkout: Checkbox for Auto-Product Addition in Cart

Based on Unique Checkbox field that adds a product to the cart on Woocommerce checkout page, I have successfully implemented the following code: It enables customers to add a specific product to their cart by simply checking a checkbox. The AJAX feature dy ...

Issue with Jquery .ajax function returning an object even after it has already moved on to the next line of code

I'm currently working with JQUERY and AJAX, and it seems like the function is somewhat functional but there's a glitch that occurs after the next line of code runs. This issue causes the script to add a null value when trying to insert the object ...

How to locate the cell with a specific class using JavaScript/jQuery

I need help with the following code snippet: var output = '<tr>'+ '<td class="class1">One</td>'+ '<td class="selected">Two</td>'+ '<td>< ...

Efficiently managing multiple form field data using a single invoice number in PHP and MySQL

I am currently working on a project involving an invoice system built using PHP/Mysqli with jQuery ajax. The table structure for the invoice table is as follows: table_invoice -> fields include (id, invoice_no, product, rate, qty). The add invoice form app ...

Incorporating conditional statements within a loop

I'm racking my brains over this issue, can you lend a hand? Currently, I am extracting data from a website. The .MyElement containers on the site store either gif or jpg URLs that I need to retrieve. In my node.js app, I am utilizing a Cheerio-base ...

Obtain the identification address for a group of items

I have a JSON object containing place IDs, and I am attempting to retrieve the corresponding addresses for each ID. This is the code snippet I'm using: <div id="places" class="places"></div> <script> function initialize() { j ...

"Easily toggle the visibility of values in checkboxes and organize them into groups with the power of JavaScript

Hey there! I am currently working on a project that involves grouping checkboxes and hiding/unhiding their content based on user interaction. Essentially, when the page first loads, the "All CARS" checkbox will be checked by default. If I then check the "C ...