Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am learning HTML/JS and I am having trouble with this script. I am practicing making buttons that preform actions but when I got to the the part of where clicking text doing actions like changing innerHTML. I have tried moving the script to a different location on the page but with no luck anytime I press the element that changes text it makes the other script do the action but not the one I clicked. I am referring to when I use
<h1>Click to change text color</h1>
<p id="siaz" onclick="myFuntion()">Click me to make my text change color!</p>
<script>
function myFuntion() {
document.getElementById("siaz").style.color='red';
}
</script>
</body>
I am only having trouble with both myFuntion() scripts. Please help. See issue for yourself by loading it in an editor.
<!DOCTYPE>
<html>
<center><font face = "Canela" fontSize = "35px" style = "color: darkblue"><h1>Just practice</h1></font></center>
<body>
<font face = "Didot"><h1>Change text</h1></font>
<p id="mill">This text will change</p>
<button type = "button" onclick = 'document.getElementById("mill").innerHTML="Changed!"'>Click to change!</button>
</body>
<body>
<font face = "Papyrus" ><h1>This will make text reappear</h1></font>
<p id="disa" style = "display:none">This text will be reappear</p>
<button type = "button" onclick = "document.getElementById('disa').style.display='block'">Click to reappear</button>
</body>
<body>
<font face = "Verdana"><h1>This will make text disappear</h1></font>
<p id="deps">This text will go away when you click that button</p>
<button type = "button" onclick = "document.getElementById('deps').style.display='none'">Click to make this text go away!</button>
</body>
<body>
<h1>This will Change the font size</h1>
<p id="clas">This should become bigger</p>
<button type = "button" onclick = "document.getElementById('clas').style.fontSize='45px'">Click to make the size bigger</button>
</body>
<body>
<h1>Click to change text color</h1>
<p id="siaz" onclick="myFuntion()">Click me to make my text change color!</p>
<script>
function myFuntion() {
document.getElementById("siaz").style.color='red';
}
</script>
</body>
<body>
<h1>Clicking the text will change the text</h1>
<p id="home" onclick = "myFuntion()">Click me, I dare you</p>
<script>
function myFuntion() {
document.getElementById('home').innerHTML="Go away"
}
</script>
</body>
</html>
You should have only one script, but you can put in as many functions as you want. You can have a changeColor function, a changeFont function (you can name then whatever you want but should have an appropriate description so it's easier to read it).
<p id="siaz" onclick="changeColor()">Click me to make my text change color!</p>
<p id="home" onclick="changeText()">Click me, I dare you</p>
<script>
function changeColor() {
document.getElementById("siaz").style.color='red';
}
function changeText() {
document.getElementById('home').innerHTML="Go away";
}
</script>
Irrespective of what you are trying to achieve, that's not the good practice to follow.
Even if you are learning
Learn the right practices at the start itself. So, a few changes needed
There can only be 1 <body> tag
Follow proper naming conventions - Method name should be a verb e.g.: changeFontColor(), changeFontSize(), etc.
Seperate html templates, styling and scripts - Use css instead of elemtents like font. No inline css or internal javascript. Keep it in separate file or in a single separate section.
Code should be properly indeneted
As you are new to this, I have shared a template for designing html pages which you could refer to start with
<!DOCTYPE>
<html>
<head>
<style>
<!-- All css styles goes here -->
</style>
</head>
<body>
<!-- All html code goes here -->
<script>
<!--All scripts goes here -->
</script>
</body>
</html>
Solution: If you could just change the
myFunction()
which changes the color to
myFunction1 or anything other than "myFunction"
at both the places (the function definition where you change the color and at the place where you are calling it, the onclick for color change) then it will start working.
Reason: As Keith said in the comments, in the global scope, we shall have unique function names, otherwise, the last one defined takes the precedence.
Best,
Sumit
Related
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
I would like to change text in P or other tag in HTML with Java Script
I tried to many different ways.
However, any of those didn't work well.
Console says.
Uncaught TypeError: Cannot set property 'textContent' of null
<script>
//1 document.getElementById("stackoverflow").textContent="newtext";
//2 document.getElementById("stackoverflow").value ="newtext";
//3 document.getElementById("stackoverflow").innerHTML ="newtext";
<script>
<div class="row">
<p id="stackoverflow">I wanna change this text</p>
</div>
Two changes
move your script after element is loaded
remove id from markup
below code works
document.getElementById("stackoverflow").textContent="newtext";
<p id="stackoverflow">I wanna change this text</p>
Check your id there is no space in between.
id is stackoverflow and your giving document.getElementById("stack overflow")
That is completly normal as long as you have two id attributes on the p tag only the first one will be consider.
let p = document.getElementById("stackoverflow");
console.log(p);
<p id id="stackoverflow">This is a sample paragraph</p>
But when you remove the first id it should work as expected
let p = document.getElementById("stackoverflow")
console.log(p);
<p id="stackoverflow">This is a sample paragraph</p>
let p = document.querySelector("p");
console.log(p.id);
<p id id="stackoverflow">This is a sample paragraph</p>
As you can see the idattribute is empty
there are 2 ways ,
1 - if you are doing onload event , u can wrap this within your body tag and call your function
2 - if its onlclick event , call this function onclick eventremove comment on button and onload = "ChangeEvent()"
<!DOCTYPE html>
<html>
<script>
function ChangeEvent() {
document.getElementById("stackoverflow").textContent = "HI";
}
</script>
<body onload="ChangeEvent()">
<p id="stackoverflow">Change</p>
<!-- <button onclick="ChangeEvent()">Clicked</button> -->
</body>
</html>
Place always your <script> tag right before the closing </body> tag
Close properly the </script> tag
<head>
<!-- HEAD stuff goes here. link, meta, title etc -->
</head>
<body>
<div class="row">
<p id="stackoverflow">I wanna change this text</p>
</div>
<!--
SCRIPTs go here before the closing </body>
-->
<script>
document.getElementById("stackoverflow").textContent="newtext";
</script>
</body>
Additional read on parser blocking versus asynchronous javascript
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm watching a basic tutorial series on javascript and have been stuck on this super simple script for like close to 30 minutes now. I used an html validator and it all checks out with no errors. However, the code is still not behaving how it should according to the video.
When you type "click me" its supposed to show a dialog box saying 'please enter a real value into the box'. And when you enter a value in the field, it's supposed to substitute the title for whatever you entered.
Sorry for the simple nooby question
EDIT AGAIN: Thanks Arby. That got it working.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script type="text/javscript">
function substitute () {
var myValue = document.getElementById(myTextBox).value;
if (myValue.length == 0){
alert('Please enter a real value in the text box!');
return;
}
var myTitle = document.getElementById('title');
MyTitle.innerHTML = myValue;
}
</script>
</head>
<body>
<h1 id="title">JavaScript Example</h1>
<input type="text" id="myTextBox" />
<input type="submit" value="Click Me" onclick="substitute()" />
</body>
</html>
I found some issues with your code, just simple stuff that every beginner goes through (I did), I'll bullet them off:
MyTitle isn't myTitle, JavaScript variables are case-sensetive.
You should stay away from the onclick attribute; he's a bad influence. The point, inline JS is generally not a good idea.
So I added an event listener event instead: [...].addEventListener("click", callback);
Your DOM request to the input box used an undefined variable/object/etc. called myTextBox, instead of a string "myTextBox".
Anyway, I made a JSFiddle for the code, so I could test it, so here is the link to the code with the edits I explained above: https://jsfiddle.net/Lktzw0Lh/
A slightly different approach - since you list jQuery in the tags for this - i have rejigged the code to take advantage of it. I put an onclick event handler on the button which, when clicked gets the value of the textbox and if it is empty - gives the alert. If it is not empty - it swaps the h1 text for the entered text and clears the text input and gives it focus so that you can re-enter new content.
Note that the click handler is in the javascript section and not inline js and also that with jquery - you can chain together commands that affect the same element.
$(document).ready(function(){
$('#testButton').click(function(){
var myValue = $('#myTextBox').val();
if (myValue == ''){
alert('Please enter a real value in the text box!');$('#myTextBox').focus()
}else{
$('#title').text(myValue);$('#myTextBox').val('').focus()
}
})
})
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h1 id="title">JavaScript Example</h1>
<input type="text" id="myTextBox" />
<button id="testButton" type="button">Click Me</button>
</body>
</html>
I have made a blog using blogger and now I want to customize it. All I want is to be able to add a button having Javascipt's onclick() in blogger's page behind HTML. I tried all the tricks but it is somehow not working.
<div>
<div>
<img src="C:\Users\dell\Desktop\goldfavicon.jpg" height="98px" width="98px"/>
</div>
<div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var btn = document.createElement("BUTTON");
window.open("http://www.amazon.com/tinny-tots-baby-bottle-cover/p/itme3h9rvenhxvxb?pid=BTCE3H9RGFD3Z7JR","_self")
}
</script>
</div>
</div>
I had the same problem recently.
You need to wrap your script like so
<script type='text/javascript'>
//<![CDATA[
function myFunction() {
var btn = document.createElement("BUTTON");
window.open("http://www.amazon.com/tinny-tots-baby-bottle-cover/p/itme3h9rvenhxvxb?pid=BTCE3H9RGFD3Z7JR","_self")
}
//]]>
</script>
The term CDATA tells the XML parser not to parse the wrapped text data. For more info on CDATA, check this answer.
Also I followed this advise:
Adding Scripts in Blogger is extremely straightforward. All you need
to do is to go to Blogger.com >> Your site >> Template >> Edit HTML.
Now it depends on you where you would like to paste your JavaScript
coding. However, we prefer you to add it above the tag because
this is the place where all technical things are present.
Hope it helps.
Here is my code:
<html>
<head>
<script type="text/javascript">
var x= document.getElementById("2").value;
document.getElementById("1").innerHtml = x;
</script>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
</body>
</html>
in this code i have a hidden tag as you can see. I want that the javascript code read text value of the p tag with an id 2 and then print the same value to other <p> tag wiht id="1". But this is not working. Earlier i even tried to use nodeValue but also this is not working and when i checked out in google developer tool then it was showing an error as following:
Cannot read property 'value/nodeValue' of null
please note:
after a quick experiment i noted that after adding a event handler <body onload="y();>" there was no error but there was no expected result!
please help!
hidden is an input element type, not a p attribute:
<input type="hidden" id="2" value="This input should be hidden." />
There are three problems:
there is no innerHtml, innerHTML is the correct syntax.
the hidden "p" does not have a value, it is not an input field. use innerHTML for accessing it.
your javascript code runs before the browser knows about paragraps, so they don't exist when you want them to be accessed. put javascript after the paragraphs or run the code after the page is loaded.
this should work:
<html>
<head>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
<script type="text/javascript">
var x= document.getElementById("2").innerHTML;
document.getElementById("1").innerHTML = x;
</script>
</body>
</html>
Don't use numbers for ID.
Try something like <p id="hello"></p>
I think you need to change your tag to then you can set a CSS class with .hidden { display:none; }.
Wrap your Javascript in a function and call it when you need to or go back to your
Also as Maaz said, try not to use numbers in your ID's.
var hiddenValue = document.getElementById('2').innerHTML;
document.getElementById('1').innerHTML = hiddenValue;
The problem with this (and if you try and style it also) is that classes and ID's should not start with (or include) numbers.
Rename your ID's to one and two and then update your javascript accordingly.
e.g
<p id="one">Some stuff</p>
Also hidden cannot be used with a p element as it's for inputs only.
You're better off using display:none; in CSS.
If you NEED to access it via css as a number, you can use
[id='1']{
/*code*/
}
but your javascript still wont work.
As James has pointed out, using numbers for ID's is perfectly valid in HTML5.
I'm trying to make a magic eight ball simulation, but it's not working for me. The inspector element in Chrome shows no errors, so I'm confused why it won't work. Any suggestions would be greatly appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Project 4: Consistent</title>
<!-- This part is the function to create my magic eight ball that will randomly give a result, but for certain questions,
it will provide the same answer always to fool their minds. -->
<script>
var answerMap = {}
var images = ['eightBallYes.png', 'eightBallNo.png', 'eightBallMillionYears.png', 'eightBallAskLater.png', 'eightBallReally.png'];
//I actually had a little bit of difficulty with this part of the project.
//The answer.search method you showed us in class for some reason is not working for me.
//I worked with the GTF on this part
function eightBall() {
var answer = document.getElementById("answerBox").value;
answer = answer.toLowerCase();
if (answer.search(/[r]/) > 0 ) {
var yes = '../Images/eightBallYes.png'
return yes;
}
if (answer.search(/[m]/) > 0 ) {
var no = '../Images/eightBallNo.png'
return no;
}
}
window.onload = alert('Welcome to my Project 4')
</script>
</head>
<body>
<body style="background:#EEEE17">
<!-- This part of the page will simulate a magic eight ball that will provide at least 4 answers.
When certain questions are asked, it will return the same answers. This is honestly a pretty cool project to work on. -->
<div style="text-align:center">
<h1>Project 4: Booyah!</h1>
<img src="../images/eightBallTemplate.png" >
<h2>Magic 8-Ball Game</h2>
<input type="text" id="answerBox" value="Please ask a question">
<input type="button" value="Submit for Magical Results" onclick='eightBall()'/>
<div id="myOutput"></div>
<hr>
Old MacDonald In-Class Activity
<br>
Parameter In-Class Activity
<br>
jQuery In-Class Activity
<br>
String In-Class Activity
<footer>
<p>
© Copyright by Alan Sylvestre
</p>
</footer>
</div>
</body>
You aren't doing anything with the return value of your function.
You probably want to assign it to the <img> tag's src property.
The problem I see is that you are calling the eightBall function when the button is clicked and the right value is chosen, but you are not doing anything with it, e.g. appending a node in the myOutput div.
You also have two body tags.