Change innerHTML on button click - javascript

I'm learning Javascript, and I'm trying to change the text of an 'id' when the user clicks a button. Here's the code:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello</p>
<button type="button" onclick="document.getElementById("demo").innerHTML = "Hey There"">Try it</button>
</body>
</html>
When I select the button, nothing happens. What am I doing wrong, and how can I fix it?

My answer will possibly look complicated at first, but I do believe that starting with a good conception is healthy and will make things more enjoyable. A common problem with learning tools actually is that they promote themselves as "QUICK" ways of learning something. There is some good you can get from them, but there is some caveats. It can be harder to learn if you skip too many steps.
HTML is by design used to describe the presentation of the page, while JavaScript is by design used to interact with that page.
Inline JavaScript is a bad practice and will often lead to issues like the one you're facing. Inline here means that you directly put interactive code inside the HTML presentation. If you do that, you will quickly find that this part of HTML becomes messy. Then, it will look hard to deal visually with delimiters since there is >, " and ' all at the same place.
Another problem with inline javascript is that it mixes two concepts: interaction and presentation. HTML should be only used for presentation.
In that way, you could edit your code to make it look like this:
HTML
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello</p>
<button id="btn" type="button">Try it</button>
<script>
document.getElementById('btn').onclick = function() {
document.getElementById('demo').innerHTML = 'Hey There';
}
</script>
</body>
</html>
What it does is when the document loads, it will interactively associate an action to your button if JavaScript is enabled in the user's browser. If it's not, the page won't fail at all, it will be downgraded. In that sample, the presentation (html) is totally separated from the interaction (script). As a bonus, there is no more f*cks with double or single quotes.
For the script part, I personnally like to work it a little bit more so it is easier to use and read.
Something like this:
JavaScript
_e('btn').onclick = function() {
_e('demo').innerHTML = 'Hey There';
}
function _e(id) {
return document.getElementById(id);
}
Or even better:
JavaScript
_e('btn').addEventListener('click', function() {
_e('demo').innerHTML = 'Hey There';
}, false);
function _e(id) {
return document.getElementById(id);
}
The last version will explicitly state your intention to do something when you click on your button. This actually makes it really clear what you intend to do with your button.
I hope this helps and good luck :)

-You are using double quote inside double quote. So it results in breaking of string like this.
onclick="document.getElementById(" its the first string and so on...
-Either you can use single quote inside double quote or double quote inside single quote.
here is the working code:
First Approach(Using single quote inside double quote):
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello</p>
<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hey There'">Try it</button>
</body>
</html>
Second Approach(Using double quote inside single quote):
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello</p>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Hey There"'>Try it</button>
</body>
</html>
More about single and double quotes Read this

The problem is that you are breaking the string because of the quotes:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello</p>
<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hey There'">Try it</button>
</body>
</html>
notice I changed the double quotes to single quotes

It's always better to have JavaScript execute in a separate function. Instead of inlining JS in the onclick attribute, try this approach:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello</p>
<button type="button" onclick="textChange()">Try it</button>
<script>
var textChange = function( ) {
document.getElementById("demo").innerHTML = "Hey There";
};
</script>
</body>
</html>
That way, on top of the fact that your code is easier to read, you will avoid the double quote/single quote issue you had.

Related

I need help understanding event handlers and functions in JavaScript?

I wrote HTML document and linked to my JS document.
when I execute the HTML file on my browser it only shows the "Click me!" button, but what I expected it to do was to show the result of my math function when clicked. But .. nothing happens. I'm very new to JavaScript so I'm sure this is a simple answer, but Googling isn't helping ... I appreciate any insight to what I'm doing wrong here.
Here's the code from HTML file:
<!DOCTYPE html>
<html lang=""en">
<head>
<meta charset="UTF-8">
<script src="JS/main.js"></script>
</head>
<body>
<p id="Math">
<button onclick="myFunction()">Click me!</button>
</p>
</body>
</html>
Here's the JS file:
function myFunction(a, b) {return a * b;}
document.getElementById("Math") .innerHTML = myFunction(13, 4);
Not sure what are you trying to do, but if you want to change the content of the "Math" element, you must call the function with parameters (eg: onclick="myFunction(1,3)") and that function should replace the content:
function myFunction(a, b) {
document.getElementById("Math").innerHTML = a * b;
}
<p id="Math">
<button onclick="myFunction(3,4)">Click me!</button>
</p>
Also if you want to preserve the button after clicking, this should be located outside the "Math" element to avoid being removed when replacing innerHTML
You’re including you script file in the header, so it runs before the dom is available. When it executes, it won’t be able to find your id, so nothing will happen. You likely will see an error in the console that your document.getElementById call is returning undefined. Either include it at the end of the body, or add a defer tag:
<script src="JS/main.js" defer></script>
Also, as soon as the code runs, it overwrites the content of the p tag, including the button. Make the p and the button siblings.
One error in your html appears to be caused by an extra " in your lang attribute for your opening html tag. Try deleting it.
<html lang="en">

Why is document not working on JavaScript

I've looked at various websites but non have helped. To me everything seems to be correct, but I can't get the
document.getElementByClassName("first").style.display="none";
to work no matter how many times I tried, I kept getting the same error message on JS;
ERROR:'document' is not defined.[no-undef]
Tried defining the 'document' part and didn't help. Maybe, I was doing the connection between external folders incorrect I tried that and nothing changed
HTML:
<html>
<head>
<script src="JS.js"></script>
</head>
<body>
<div class="first">
<p>Hello and welcome to my first page<br>
in this page I will test out new think<br>
and see what works and what doesn't<br>
</p>
</div>
<button type="button" onclick="myFunction">Click me</button>
</body>
</html>
JS:
function myFunction(){
document.getElementsByClassName("first").style.display="none";
The button is suppose to clear all he style's from "first".I've changed many outcomes and have nothing happen to the code just the same error repeating its-self over and over again.
document.getElementByClassName() returns an array of elements, so you'll need the index of the element you want to target.
You should call the function by myFunction() and add [0] to getElementsByClassName to get specific element.
function myFunction() {
document.getElementsByClassName("first")[0].style.display="none";
}
<html>
<head>
<script src="JS.js"></script>
</head>
<body>
<div class="first">
<p>Hello and welcome to my first page<br>
in this page I will test out new think<br>
and see what works and what doesn't<br>
</p>
</div>
<button type="button" onclick="myFunction()">Click me</button>
</body>
</html>
It seams that the error you are recieving comes from a linter, but has nothing to do with your code not working. To fix your linter issue, you might want to have a look at this post.
For errors that are produced at runtime, you should have a look at your browser console (In most cases opened with F12).
In regards to your main issue, there are two things to fix:
1)
Your inline onclick handler should be called like so:
<button type="button" onclick="myFunction()">Click me</button>
2)
Instead of using document.getElementsByClassName() - which returns an array -
I recommend you to use document.querySelector() instead, as it returns just the first element it found and is much easier to use, if you are already familiar with css selectors.
For more information an the querySelector-function have a look at this page.
So, in your code it should look like this:
function myFunction() {
document.querySelector(".first").style.display="none";
}

How to put an internal script inside a div tag?

I am trying to run a javascript inside of a div tag because i have heard its possible but for some reason the code does nothing.
<!DOCTYPE html>
<html>
<body>
<title>XDSITE</title>
<br>
<br>
<div id=mycode style="BACKGROUND:
url('javascript:eval(window.alert("sometext"))'"></div>
</body>
</html>
You have some problems in your HTML it is not valid, you can't run JavaScript from a style attribute.
You can run Javascript from within a <script> tag which really is the best way to do it.
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Alternatively there are some HTML elements that allow you to execute it on some events, like onchange, onclick etc.
<select onchange="myFunction()">
<button onclick="myFunction()">Click me</button>
https://www.w3schools.com/ is a great resource for learning more about each html element, and also JavaScript as a whole.
Good luck
can you please tell here which java script framework is you are using? you can achieve this by using and template java script framework like Angular, React...
If u dont want to use any framework than you need to write pure javascript or jquery code for assigning the background css prop.
for entire body,
document.body.style.backgroundImage = "url('img_tree.png')";
for div,
document.getElementById("mycode").style.backgroundImage = "url('img_tree.png')";
<!-- U have to give event inside expression like onclick ,mouseup Click that text -->
<div id=mycode onclick="alert('Hi ....sometext')">THARA
</div>
<!DOCTYPE html> <html> <body> <title>XDSITE</title> <br> <br> <div id=mycode style="BACKGROUND: url('javascript:eval(window.alert("sometext"))'"></div> </body> </html>
Answer :
Open script in footer
<script>
$( "#mycode" ).click(function() {
alert( "Hai" );
});
</script>
I hope its working for you ...
You can target HTML tag using getElementById() and then apply custom style like this
document.getElementById("Mydiv").style.backgroundColor="#0000"
or apply a bunch of styles like this
var dev = document.getElementById("Mydiv");
dev.style.backgroundColor="#0000";
dev.style.fontSize="..";
dev.style.backgroundImage="..";
You can run your function using "onerror" event. And also you must do some error in that case. For eg.
<img src="someFakeSrc" onerror='javascript:eval(window.alert("sometext"))'>
HTML doesn't see a src of picture then run a 'onerror' event.

HTML will not execute JavaScript functions

I am trying to get a very simple javascript project going, but I cannot get any function to execute. Here is a simple example. It is obviously just an example. I have tried everything I can think of to get the browser to recognize that I am trying to call a function that has been defined, but it never does anything but just display the text, rather than call anything. In the below example, I simply get a page with the text: "varTimesTwo(3);"
<!DOCtype html>
<html>
<body>
<script>
function varTimesTwo(oneVar){
return (oneVar * 2)
}
</script>
varTimesTwo(3);
</body>
</html>
your code is wrong, you have to place varTimesTwo(3); inside the script tag, like this:
<!DOCtype html>
<html>
<body>
<script>
function varTimesTwo(oneVar){
return (oneVar * 2)
}
varTimesTwo(3);
</script>
</body>
</html>
Keep all JavaScript code in the script tags, or better yet, in a file
separate from the html file using <script src="myjsfile.js"></script>
You can use document.write(string) to write a string to the document.
This string is treated as HTML so you need to use <p>text</p> or <br> to get line breaks.
<!DOCtype html>
<html>
<body>
<script>
function varTimesTwo(oneVar){
return (oneVar * 2)
}
document.write("3 times two is "+varTimesTwo(3));
</script>
</body>
</html>
Alternatively, you can use window.alert(string) or simply alert(string) to pop up an alert box. But if you have turned off pop-ups in the browser, these will not pop up.
<!DOCtype html>
<html>
<body>
<script>
function varTimesTwo(oneVar){
return (oneVar * 2)
}
alert("3 times two is "+varTimesTwo(3));
</script>
</body>
</html>
console.log(string) writes to the debugging console, which you can see on many browsers with either control-shift-J or F12.
The javascript debugging console is also useful for learning javascript without messing with input and output. Anything you type in the JS console is immediately executed, so you can define functions there and play with them without having to write additional code to write the output or read input.
Finally, these techniques are insufficient for most websites as they are actually used. Instead, what is done is to define an html container element and change the text or html that is inside. jQuery provides a browser-independent method of manipulating the document to change items on the page.

Why doesn't innerHTML work with white spaces?

In the below html, the front button doesn't respond while the back button changes the content of the tag.
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button onClick=document.getElementById('para').innerHTML="move front">
front
</button>
<button onClick=document.getElementById('para').innerHTML="back">
back
</button>
</body>
</html>
In the below, both the buttons change the content of the tag.
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button onClick=document.getElementById('para').innerHTML="movefront">
front
</button>
<button onClick=document.getElementById('para').innerHTML="back">
back
</button>
</body>
</html>
Why does a bank space make a button unresponsive?
That is just invalid HTML.
You have to put quotes around your whole onclick attribute value, otherwise it will end at the space.
onClick = document.getElementById('para').innerHTML="move // cut off here
front" // a second (meaningless) attribute for your button tag.
Please consider this syntax:
<button onclick="document.getElementById('para').innerHTML='move front'">front</button>
You are probably having issues if you are using this technique.
I am sorry but this is not how you attach a click event to elements in modern javascript, at least if you want to work with what's called "good practices".
The better method would be to attach a click event to a desired element using javascript.
I will give you a short code example.
First the HTML - I will use your original HTML (modified a bit):
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button id="frontBtn"> front </button>
<button id="backBtn"> back </button>
</body>
</html>
As you can see, I have removed your "onclick" events from the buttons, and assigned an id to each button.
Second, we will write some javascript to properly attach a click event to each one of the buttons, and of course execute the change of text as you originally was intending to do:
if you are familiar with jQuery then this will do:
$('#frontBtn').on('click',function(){
$('#para').html('move front');
});
$('#backBtn').on('click',function(){
$('#para').html('back');
});
This can also be done with vanilla (native) javascript:
document.getElementById("frontBtn").addEventListener("click", function(){
document.getElementById("para").innerHTML = "move front";
});
document.getElementById("backBtn").addEventListener("click", function(){
document.getElementById("para").innerHTML = "back";
});
Now we have a nicely structured event handler for each button, more code can be easily added.
As for where to insert your javascript ?
You can add the javascript to your html document by using script tags in your html document head like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// your code here..
</script>
</head>
<body>
....
....
Or even better - create a separate script file and load it at the bottom of your html page like this:
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
....
....
<script type="text/javascript" src="scripts.js"></script>
</body>
</html>
This is the better way to attach events to elements, using javascript.
Imagine if you try to write 50-100 lines of code inline ? impossible! but with an event handler function you can do it easily.
Things will basically work better and your project will be much easier for you to maintain.
Hope it helps a bit!

Categories

Resources