Stopping the sound when its' Div is hovered over

I've managed to successfully trigger the audio to play on hover, but I'm having trouble getting it to pause when my mouse leaves the area.

Check out the code in action here: https://jsfiddle.net/jzhang172/nLm9bxnw/1/

$(document).ready(function(){
var audio = $("#audio-1")[0];
$(".box").hover
(function() {
    audio.play();
  },
(function(){
 audio.stop();
});
});
.box{
  height:500px;
  width:500px;
  display:flex;
  justify-content:center;
  align-items:center;
  font-size:25px;
  color:white;
  background:black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio controls id="audio-1">
  <source src="http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

<div class="box">
If you Hover me, the song will play!
</div>

Answer №1

Make sure to utilize audio.pause() instead of .stop(). See the code snippet below for an example:

$(document).ready(function(){
  var audio = $("#audio-1")[0];
  $('.box').on({
    mouseenter: function() {
      audio.play();
    },
    mouseleave: function() {
      audio.pause();
    }
  });
});

To resume playback from where it left off, simply use the method as shown above. If you wish to restart from the beginning (as another user mentioned), include audio.currentTime = 0; before the start or after the pause command.

You can view a working example on JSFiddle here: https://jsfiddle.net/nLm9bxnw/7/

Answer №2

halt is not a commonly used JavaScript method for manipulating audio and video files. Instead, consider using one of the following alternatives:

audio.pause();
audio.currentTime = 0;

For more information, check out this discussion on Stack Overflow

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

Highlighting JavaScript code with React Syntax Highlighter exclusively

I've been struggling to highlight Ruby code, but it seems like no matter what I do, it keeps highlighting JavaScript instead. It's frustrating because I can't seem to get it right. import React from "react"; import atom from "node_module ...

Passing along the mouse event to the containing canvas element that utilizes chart.js

Recently, I created a custom tooltip for my chart.js chart by implementing a div that moves above the chart. While it works well, I noticed that the tooltip is capturing mouse events rather than propagating them to the parent element (the chart) for updati ...

modify hidden input values with a dropdown menu and the power of jquery

Hey there, I could really use some help with a challenge I'm facing. I'm currently working on an ecommerce website for my girlfriend and incorporating foxycart for handling the cart functionality. However, I'm stuck at a point where I need t ...

Running concurrent codes is not possible in Node.js serialport

I am attempting to stream data from the MSP432 xds110 in order to display it on my website in real-time. To achieve this, I have opted to utilize the node.js serialport library for data retrieval. You can find more information about serialport here: In m ...

Instructions for embedding a swf file in HTML and linking it to a different page

I've employed the following code snippet to embed my SWF file and redirect it to another page upon clicking: <object type="application/x-shockwave-flash" onmouseup="document.location='http://www.pageopensafterclick.com'" height=50 width= ...

What is the best way to incorporate Vue.js into a Django project?

We are currently working on a school project that involves creating a complete website using Django and Vue. However, we are facing challenges when it comes to integrating Vue into our Django project. In order to simplify things, we have decided to use Vu ...

Bringing in two JavaScript files with identical names

Recently, I encountered a challenging situation. I am working with material-ui and nextjs, both of which have a module called Link that is essential for my project. import { Link } from '@material-ui/core'; However, this setup is causing compil ...

How to trigger a JavaScript function using a button click

I've been struggling to figure out why my JavaScript code isn't functioning properly within Ionic. Can anyone guide me on how to store a number in a variable, display that variable, and increment it when a button is clicked? I have successfully ...

Having trouble grasping the functionality of Javascript in this code (using Coffeescript and Commander in Node.js)

I'm facing some issues when using Commander in Node.js - the parseInt function doesn't seem to be working correctly in my code: commander = require 'commander' #parseInt = (str) => parseInt str #I attempted to add this line witho ...

What are the steps to resolve the error 'content-type missing boundary' and encountering the issue with getBoundary not being recognized as a function?

fetchCarouselData: async (params) => { let bodyFormData = new FormData(); for (let prop in params) { bodyFormData.append(prop, params[prop]); } return axios({ method: "post", url: `${baseURL}/fetchCarouselData`, data: b ...

Issue with JQuery: Fancybox not functioning properly within Google Maps

While working with a Google Map, I encountered an issue where I needed to allow users to expand images within the map itself. Fancybox seemed like the perfect solution for this, but unfortunately it is not functioning as expected. Link to example In the ...

Configuration of an MVC-based web application

As a newcomer to web application development, I am currently working on building a web application using the Model-View-Controller pattern. My setup includes a MySQL database for the Model, JSP pages for the Views, and a DAO for the Controller. I am looki ...

Modify the Ng-Pattern with Jquery

Is there a way for someone to assist me in updating the Ng-Pattern with Jquery? I have looked at the questions below, but they haven't been helpful (Most of them focus on updating to dynamic values using Angular JS). Question 1 Question 2 Question ...

Enclose a pair of divs within a fresh div wrapper for better organization

Imagine you have the following: <div class="somediv"></div> <div class="somediv"></div> <div class="somediv"></div> <div class="somediv"></div> <div class="somediv"></div> <div class="somediv" ...

Meteor, enhanced with the dynamic Iron Router module and integrated

I am working on a project using Meteor (Meteor.com) and I want to incorporate iron-router for the page routing along with the pre-existing accounts-ui package for login functionality. Previously, my {{loginButtons}} functioned properly, but ever since I i ...

What is the best way to utilize the .done() callback in order to execute a function when new data is loaded upon request?

I have a web page that pulls data from a JSON feed, and there's also a button to load more content from the feed when clicked. I want to add additional elements inside the page for each item in the feed. I've managed to create a function that doe ...

Creating adaptable HTML images by specifying width and height attributes within the image tag

My current website setup involves loading a full image and automatically adjusting its size to fit the screen by setting the image width to 100% in CSS. While this method works smoothly, it may not be following standards as I am not specifying width and he ...

Node.js Express application: Managing endpoint conflicts

After searching for a solution to this issue and not finding one, I apologize if this question is repetitive. In my express+node.js application, I have two endpoints defined as follows: // Retrieves a tweet by unique id app.get('/tweets:id', fu ...

How to Implement Force Unmount in Vue 3 When Deactivated

I've developed a VUE app that makes use of the keep-alive method in the router. There are multiple pages that should only be loaded once, but certain specific pages need to be reloaded every time they are activated. <template> <router-view ...

Customizing the background color in TurnJSIncorporating

Recently, I encountered a problem that has left me puzzled. Despite searching online for help, I have not been able to find a solution. The issue lies with the basic code provided on the official page of the TurnJS script. <div id="flipbook"> <di ...