Home > Software engineering >  how can i give a button two seperate functions in html
how can i give a button two seperate functions in html

Time:01-30

so im trying to create a button that takes you to the second page of my website aswell as playing a sound file. the problem im having is that it goes to the second page without playing the sound. currently, my code looks like this:

<body>
    <audio id="sound1" src="sound.mp3" preload="auto"></audio>

    <button type="submit" onclick="document.getElementById('sound1').play(); 
    location.href='page2.html';">enter</button>
</body>

does anyone know why this is happening, and if so, how can i fix it.

CodePudding user response:

When navigating to a new page, the previous page's lifecycle ends, including media that's playing. Consider using a Single Page Application (SPA) pattern to change URLs and content while maintaining playing audio.

CodePudding user response:

Same issue here when then i write this code and done

function playAndRedirect() {
  (<HTMLAudioElement>document.getElementById('sound1')).play()
  window.open('http://stackoverflow.com pass your page URL here', '_blank');
}

Write this and its work.

CodePudding user response:

I think you should create a new function write all your code in it. Then you can achieve both things.

function playAndRedirect() {
   (<HTMLAudioElement>document.getElementById('sound1')).play()
  window.open('http://stackoverflow.com pass your page URL here', '_blank');
}
  •  Tags:  
  • Related