Search code examples
javascripthtmlonmouseoveronmouseout

Using this and document.getElementById within an img onmouseover function


I'm trying to change an image and the text inside an h2 using onmouseover and onmouseout, like in this gif

enter image description here

I give some examples below where I can change the image with onmouseover and onmouseout using either this or document.getElementById, but when I use this I can't figure out how to simultaneously change the text inside the h2 tag(like in the example under document.getElementById). Using the following snippet does not change the image.

onmouseover='(function(){
                this.src="https://i.imgur.com/dsF2mgL.jpg"
                document.getElementById("message").innerHTML="I am so very tired"
            })()'

I am looking for a way to use this and change both the image and the text inside the h2


Using document.getElementById

    <h2>ICE 14: Drake the Duck</h2>
    <img
        id="duck"   
        src="https://i.imgur.com/G8TcUqA.jpg"
        onmouseover='(function(){
            //this.src="./duck2.jpg"
            document.getElementById("duck").src="https://i.imgur.com/dsF2mgL.jpg"
            document.getElementById("message").innerHTML="I am so very tired"
        })()'
        onmouseout='(function(){
            document.getElementById("duck").src="https://i.imgur.com/PKi5s3p.jpg"
            document.getElementById("message").innerHTML="Now I am wide awake!"
        })()'
    >
    <h2 id="message">I am Drake the Duck.</h2>

Using this

        <h2>ICE 14: Drake the Duck</h2>
        <img
            id="duck"   
            src="https://i.imgur.com/G8TcUqA.jpg"
            onmouseover='this.src="https://i.imgur.com/dsF2mgL.jpg"'
            onmouseout='this.src="https://i.imgur.com/PKi5s3p.jpg"'
        >
        <h2 id="message">I am Drake the Duck.</h2>


Solution

  • Don't use an IIFE in the onclick attribute, because this is not inherited by functions (unless you use an arrow function). You can just put the code directly in the onclick attribute without the function wrapper.

    <h2>ICE 14: Drake the Duck</h2>
    <img id="duck" src="https://i.imgur.com/G8TcUqA.jpg"
        onmouseover='this.src="https://i.imgur.com/dsF2mgL.jpg"; document.getElementById("message").innerHTML="I am so very tired"' 
        onmouseout='this.src="https://i.imgur.com/PKi5s3p.jpg"; document.getElementById("message").innerHTML="Now I am wide awake!"'>
    <h2 id="message">I am Drake the Duck.</h2>