Jean-Luc Godard
Jean-Luc Godard

Reputation: 1883

onClick event not getting called in JavaScript

I am writing my first code in JavaScript.

I want to do this :-

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.

Upvotes: 2

Views: 225

Answers (3)

John
John

Reputation: 145

i think u can use alert( "It is good to meet you, "+ userName + "." ) ;

instead of alert("It is good to meet you, " "+userName+ " ".");

As per my knowledge, in javascript we usually use "+" symbol for concatenation .

Upvotes: 1

bennick
bennick

Reputation: 1917

You are not preforming string concatenation correctly in your alert.

Change this:

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

To this:

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

To concatenate two strings together the + operator must sit outside of the strings.

var newString = "I am " + "a concatenated string";

Upvotes: 1

PSL
PSL

Reputation: 123739

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

Upvotes: 7

Related Questions