Learn how to trigger a sound by clicking on a hyperlink

<audio id='aclick'>
  <source src="audio/click.mp3" type="audio/mpeg">
</audio>

$(document).click(function(){
    if (click == 1) {
        document.getElementById("aclick").play();
    }
});

Everything is working smoothly except for hyperlinks.

I want the sound to play when clicking on any element, even hyperlinks.

Answer №1

Enhanced Solution :

$('a').click(function (e) {
    e.preventDefault();                   // stop anchor default behavior
    var goTo = this.getAttribute("href"); // save anchor's href

    // perform an action when timeOut expires ... 
    $("#aclick")[0].play();

    setTimeout(function(){
         window.location = goTo;
    },3000);       
});

Past solution :

trigger function on any click event

 jQuery( 'body' )
    .click(function() {
        alert("");
        $("#aclick")[0].play();
        return false;
    });

invoke function on click of any anchor tag

jQuery( 'a' )
    .click(function() {
        alert("");
        $("#aclick")[0].play();
        return false;
    });

Answer №2

Clicking on a hyperlink attempts to redirect you to the href destination. To prevent this redirection, use e.preventDefault(); and trigger a sound effect.

$(document).click(function(e){
    e.preventDefault();
    if (click == 1) {       
        document.getElementById("aclick").play();
    }
});

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

Using JSDoc, consider a Plain Old JavaScript Object (POJO) as an instance

When working with a class and a function that accepts an instance of that class or a similar POJO object, there is a desire to use JSDoc annotations. class Example { constructor(x, y) { this.x = x; this.y = y; } } /** * @param {E ...

Looking to transform a nested JSON structure into a visually appealing HTML table with merged rows?

My JSON structure appears as follows: $scope.data = [ { "type":"Internal", "count": 3, "library" : [ { "type":"Library 123", "count": 2, "version" ...

Creating an OAuth2 Request in Node.js

As I delve into constructing an OAuth2 request for the Box API, I find the example POST request provided a bit perplexing. This is mainly due to my recent foray into backend development. The example in question reads as follows: POST /token Content-Type: ...

Utilizing JavaScript to Decode XML

Trying to access XML elements within a document that contains around 935 AircraftReport items. I am familiar with displaying all of them using the .find() and .each() methods, but I am specifically struggling with retrieving only the first 10 AircraftRepor ...

Node.js Timer Functionality for Precision Timing

I'm currently in the process of developing a live chess application and one feature I'm looking to incorporate is a timer. The challenge I'm facing lies in ensuring the timer is accurate. After conducting various tests, I discovered that bot ...

Learn how to dynamically switch the background image of a webpage using a button in AngularJS

Hey there, I'm currently working on incorporating interactive buttons into my website to give users the ability to customize the background. I've been experimenting with Angular to achieve this feature. So far, I've managed to change the ba ...

Issue with Vue directive bind not functioning after element refresh

My approach involves utilizing vue.js to create forms, where all fields are structured within a JavaScript objects array. Here is an example of the structure I use: { type: "input", mask: "date", default: "2018/04/14" }, { type: "input", ...

Looking to pass multiple props and run a function for each one? Here's how!

There is a scenario where I have two separate times in minutes format that need to be converted to 24-hour format without separators. I am currently using a function for this conversion and then using momentjs to transform it into the required format. Whil ...

Using *ngIf can lead to a never-ending cycle that never gets resolved

I am currently working on a project using Angular and I need to conditionally display a form based on certain values. I have successfully tested the backend route using Postman and everything is functioning correctly. Here is a snippet of my code: Block ...

Having trouble with the Slide Menu Javascript functionality

Having some trouble creating a sliding menu with jQuery. Errors on lines 5 and 6 saying functions are not defined. Can anyone help me figure out what's wrong with my code? jQuery(function($) { "use strict"; $(document).ready(function () { ...

Utilize Services without creating circular interdependencies

My app utilizes a GlobalDataService (GDS) to store all data globally. GlobalDataService (GDS) angular .module('app.core') .service('GlobalDataService', GlobalDataService); GlobalDataService.$inject = ['$http&a ...

Extract information from an external HTML table and store it in an array

I am looking for a way to extract data from an HTML table on an external site and save it as a JSON file for further manipulation. Is there a method to retrieve table data from an external HTML site that differs from the code example provided? Additional ...

Utilizing ES6 Map type in TypeScript for Angular 2 Response Data Transfer Object Definition

Is it possible to utilize the es6 Map type in an HTTP Response DTO? Let's consider an Angular 2 request: public loadFoos(): Observable<FoosWrapper> { return this.http.get("/api/foo") .map(res => res.json()); } Now, take a loo ...

How to Implement Jquery Confirm in Laravel Form Opening?

I've set up a Form using the Laravel Form package. {!! Form::open(['action' => ['Test\\BlogController@destroy', $thread->id], 'method' => 'delete', 'onsubmit' => 'Confirm() ...

Selecting an object from JSON data with Angular using $routeParams

I am attempting to showcase information from a JSON file that is structured like this: [ { "category":"category1", "link":"category1", "expand":false, "keyword":"category1, category1 online, category1 something" }, { "category":" ...

Unresponsive IE browser: Issues with jQuery event changes and click functionalities

Here is the HTML code: <div class="sss"> <label class="label_radio" for="radio-01"> <input name="vtip" id="radio-01" value="50" type="radio" /> <img src="http://www.tui-travelcenter.ro/layouts/innobyte/images/radio ...

When a child component sends props to the parent's useState in React, it may result in the return value being undefined

Is there a way to avoid getting 'undefined' when trying to pass props from a child component to the parent component's useState value? Child component const FilterSelect = props => { const [filterUser, setFilterUser] = useState('a ...

Discovering Node JS: Pinging UDP between Server and Client

I am new to developing in node.js and I am looking to create a simple script for pinging. My goal is to have the client send a ping to the server, have the server acknowledge it by logging the message in the console, and then send the same packet back to t ...

The power of selenium meets the functionality of Javascript with the webdriver

Encountering an issue with Selenium JS Components are created in JSON format as follows: "usernameInputField": { "selector": { "xpath": "//*[@id='username']" } } For invoking webdriver, the following is used: var webdriver = ...

Unable to integrate npm package into Nuxt.js, encountering issues with [vue-star-rating] plugin

Just starting with nuxt js and running into issues when trying to add npm packages. Below are my attempts. star-raing.js import Vue from 'vue' import StarsRatings from 'vue-star-rating' Vue.use(StarsRatings) nuxt.config.js plugi ...