Ministrelle
Ministrelle

Reputation: 13

Play music on hover?

So Basically, this is for customixing a profile layout on a website.

I do not have access to change the websites html and I know that there is no <audio> tag on the webpage. But I can import external scripts like javascript, css etc.

So I wanted to ask if there is any way to modify a <img> or <a> tag to additionally play a music file on mouse over with css, jscript or another language.

Upvotes: 1

Views: 1668

Answers (2)

HereIronman7746
HereIronman7746

Reputation: 11

OK, so the answer above mine is not quite right, to be honest, it starts playing, but it doesn't stop because music.stop(); doesn't exist you should use:

music.pause(); - to pause audio
music.currentTime = 0; - to make audio go from start.

var item = document.getElementById("img");
var music = new Audio('music.mp3');

item.addEventListener("mouseover", playMusic, false);
item.addEventListener("mouseout", stopMusic, false);

function playMusic() {
   music.play();
}

function stopMusic() {
   music.pause();
   music.currentTime = 0;
}

If you want to just let it continue on the next hover from where it ended use this:

var item = document.getElementById("img");
var music = new Audio('music.mp3');

item.addEventListener("mouseover", playMusic, false);
item.addEventListener("mouseout", pauseMusic, false);

function playMusic() {
   music.play();
}

function pauseMusic() {
   music.pause();
}

Upvotes: 1

Iwryo
Iwryo

Reputation: 41

In javascript:

var item = document.getElementById("img");
var music = new Audio('music.mp3');

item.addEventListener("mouseover", playMusic, false);
item.addEventListener("mouseout", stopMusic, false);

function playMusic() {
   music.play();
}

function stopMusic() {
   music.stop();
}

Upvotes: 3

Related Questions