Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick event not getting called in JavaScript

I am writing my first code in JavaScript.

I want to do this :-

  • Load an image
  • Ask for user name
  • after writing the name change the image
  • and show user's name in alert

My code goes like this:

<!DOCTYPE html>
<html>
<head>
<title>iRock - First Project</title>
<script type = "text/javascript">

function touchRock(){

    var userName = prompt ("what is your name?","Enter your name here.");

    if(userName){
        alert("It is good to meet you, " "+userName+ " ".");
        document.getElementById("firstImg").src="1.jpg";
    }
}

</script>
</head>

<body onload = "alert('hello, I am your pet.');">
        <div style = "margin-top:100px; text-align:centre">
                 <img id="firstImg" src="http://www.smiley-faces.org/wallpaper/smiley-face-wallpaper-widescreen-001.jpg" alt="iRock" style="cursor:pointer" onclick="touchRock()" />
        </div>
    </body>
</html>

Can anyone please tell me what is wrong in this? The event is not getting called after touching the image.

like image 448
Jean-Luc Godard Avatar asked Feb 09 '26 20:02

Jean-Luc Godard


1 Answers

Your string concatination is wrong inside the function

alert("It is good to meet you, " "+userName+ " "."); you must be getting error in the console.

Check this

function touchRock(){

    var userName = prompt ("what is your name?","Enter your name here.");

    if(userName){
        alert("It is good to meet you, " + userName +  ".");
        document.getElementById("firstImg").src="1.jpg";
    }
}

if you are using Chrome. press F12 --> you will get developer tool bar enabled, in that there will be console where you can see any errors, debug javascript inspect elements etc.. SImilarly you have Firebug for FireFox and DevToolbar for Int Explorer.

Script Debugger in Chrome - Ref

like image 157
PSL Avatar answered Feb 15 '26 12:02

PSL