Rahul
Rahul

Reputation: 1

Onclick function in img tag

I am trying to make an image clickable, that when we click on the image touchRock() function will be called and image changes accordingly. Here is the code:

<tittle> iRock - The Virtual Pet </tittle>
    <script type ="text/JavaScript">
    function touchRock(){
        var userName = prompt("What is ur userName??" , "Enter name here .");

        if (userName != null){
            alert("It is good to meet you " + userName + "."};
            document.getElementId("rockImg").src="joker.jpg";
            
            
        }
    }
    </script>
    
</head>

<body onload = "alert('hello, I am ur pet rock');">
    <div style "margin-top:400px; text-align:center">
    <img id="rockImg" src="irock.jpg" alt="iRock" style="cursor:pointer" onclick="touchRock();"/>
    


    
    
    </div>
</body>

Please help me.

Upvotes: 0

Views: 316

Answers (1)

Alexander
Alexander

Reputation: 2297

U shall use document.getElementById, not document.getElementId. And U have syntax error in

alert("It is good to meet you " + userName + "."};

Try this:

<html>
<head>
    <tittle> iRock - The Virtual Pet </tittle>
    <script type ="text/JavaScript">
        function touchRock(){
            var userName = prompt("What is ur userName??" , "Enter name here .");

            if (userName != null){
                alert("It is good to meet you " + userName + ".");
                document.getElementById("rockImg").src="joker.jpg";


            }
        }
    </script>
</head>
<body onload="alert('hello, I am ur pet rock');">
    <div style "margin-top:400px; text-align:center">
        <img id="rockImg" src="irock.jpg" alt="iRock" style="cursor:pointer" onclick="touchRock();"/>
    </div>
</body>
</html>

Upvotes: 1

Related Questions