I'm working on a part of a website where I need to have an image that plays music on click and also puts text underneath. The music part was easy, but I am lost on the text part.
Anyone have any clue? If so can you provide the code? I'm more of an HTML/CSS person so I don't understand Javascript well, lol.
I have not tried anything yet, srry
Adding text underneath an image that plays music on click is straightforward. Here's a breakdown of how you can implement it:
Steps:
or element to display the text underneath the image.
Here's a example code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Music Image</title>
<style>
#music-container {
max-width: 300px;
margin: 50px auto;
text-align: center;
font-family: Arial, sans-serif;
}
#music-image {
cursor: pointer;
width: 100%;
height: auto;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: transform 0.2s;
}
#music-image:hover {
transform: scale(1.05);
}
#music-text {
margin-top: 15px;
font-size: 18px;
color: #555;
}
</style>
</head>
<body>
<div id="music-container">
<img
id="music-image"
src="https://picsum.photos/300"
alt="Click to play music"
/>
<p id="music-text">Click the image to play music</p>
</div>
<!-- Add a random song -->
<audio id="music-audio" src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"></audio>
<script>
const musicImage = document.getElementById('music-image');
const musicText = document.getElementById('music-text');
const musicAudio = document.getElementById('music-audio');
let isPlaying = false;
musicImage.addEventListener('click', () => {
if (!isPlaying) {
musicAudio.play();
musicText.textContent = "Playing music... 🎵";
isPlaying = true;
} else {
musicAudio.pause();
musicText.textContent = "Music paused. ⏸️";
isPlaying = false;
}
});
// Add an event listener to reset text when the music ends
musicAudio.addEventListener('ended', () => {
musicText.textContent = "Music ended. Click the image to play again.";
isPlaying = false;
});
</script>
</body>
</html>