ambitiousmind
ambitiousmind

Reputation: 15

JavaScript assistance with code

I wrote these few lines of code and would like the text to change once the button is pressed but its not working. Could you please find out the problem?

var omari = "Omari Lamar";
function omari (){
    el = document.getElementById('slice');
    el.textContent = omari + "Is a computer Programmer!";
}
<html>
    <head>
        <title></title>
    </head>
    <body>
       <h1>Title Example</h1>
       <button onclick="omari();">Click me</button>
       <div id="slice">
           sample text
       </div>
       <script src="app.js"></script>
   </body>
</html>

Upvotes: -1

Views: 51

Answers (3)

Sergio Fernandez
Sergio Fernandez

Reputation: 381

this is the problem: you have a variable named omari and a function name omari. so, when you try calling the function omari, javascript actually looks at the variable definition, and not the function. just give them different name.

try the code below.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>test</title>
</head>

<body>
<script>

    var _omari ="Omari Lamar";
    function omari(){
        el = document.getElementById('slice');
        el.innerHTML = _omari + " Is a computer Programmer!";

    }
</script>

            <h1>Title Example</h1>

            <button onclick="omari();">Click me</button>
            <div id="slice">
            sample text
            </div>

</body>
</html>

Upvotes: -1

Luthando Ntsekwa
Luthando Ntsekwa

Reputation: 4218

Here you go, Your function name and variable name were the same

var omary ="Omari Lamar";
var omari = function(){
	var el = document.getElementById('slice');
	el.innerHTML = omary + "Is a computer Programmer!";

};
<html>	
	<head>
		<title>

		</title>
		<script src="app.js"></script>
	</head>
	<body>
		<h1>Title Example</h1>

		<button onclick="omari();">Click me</button>
		<div id="slice">
		sample text
		</div>

		<script src="app.js"></script>
	</body>
</html>

Upvotes: -1

Tal Avissar
Tal Avissar

Reputation: 10304

Change the code to:

var omariName ="Omari Lamar";
function omari (){
    el = document.getElementById('slice');
    el.textContent = omariName + "Is a computer Programmer!";

}

Upvotes: 2

Related Questions