Question

Is there any way to call a Javascript function from a mouse over in HTML?

I have the following code:

<script src="navSound.js" type="text/javascript"></script>

<a href="#" onmouseover="bubble2.playclip()"><li class="navBackground"><div class="navButton">Gallery</div></li></a>

I would like it to call a function named "playclip()" which is in an external file linked to the HTML document named navSound.js

Any ideas?

Was it helpful?

Solution

Yes, it is possible like so:

<html>
<head>

<script type='text/javascript'>

function playclip() {
    alert('playing clip...');
}

</script>

</head>
<body>

<a href="#" onmouseover="playclip()"><li class="navBackground"><div class="navButton">Gallery</div></li></a>

</body>
</html>

In your case, the playclip() function will be inside the external file "navSound.js" included in the script tag using the 'src' attribute.

UPDATE:

I updated your Fiddle with and you can see the changes here which work well:

http://jsfiddle.net/Lb966/ (beware: you'd hear a horse's neiggggggghhhhhhhhhhhhhh ;)

I am also pasting the markup + code below:

<html>
<head>
<script type='text/javascript'>

window.onload = function() {

    var html5_audiotypes={ //define list of audio file extensions and their associated audio types. Add to it if your specified audio file isn't on this list:
        "mp3": "audio/mpeg",
        "mp4": "audio/mp4",
        "ogg": "audio/ogg",
        "wav": "audio/wav"
    }

    function createsoundbite(sound){
        var html5audio=document.createElement('audio');
        if (html5audio.canPlayType){ //check support for HTML5 audio
            for (var i=0; i<arguments.length; i++){
                var sourceel=document.createElement('source')
                sourceel.setAttribute('src', arguments[i])
                if (arguments[i].match(/\.(\w+)$/i))
                    sourceel.setAttribute('type', html5_audiotypes[RegExp.$1])
                html5audio.appendChild(sourceel)
            }
            html5audio.load()
            html5audio.playclip=function(){
                //html5audio.pause()
                html5audio.currentTime=0
                html5audio.play()
            }
            return html5audio
        }
        else{
            return {playclip:function(){throw new Error("Your browser doesn't support HTML5 audio unfortunately")}}
        }
    }

    var audio = createsoundbite("http://www.w3schools.com/html/horse.ogg");
    audio.setAttribute('id', 'myAudio');
    document.getElementById('content').appendChild(audio);

}

</script>
</head>
<body>
<div id='content'></div>
<a href="#" onmouseover="document.getElementById('myAudio').play()">Gallery</a>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top