Calling javascript function in html second time - javascript

Below is my code for a simple text based game that i am trying to make but i cannot understand why the first time i call my function with a hyperlink 'link1', it works but when i add another link to my html document using javascript, and try to call another function onclick upon that link, it doesn't work. can somebody explain?
var getupvar = document.getElementById("attack");
getupvar.onclick = attack;
function attack() {
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
}
var link2event = document.getElementById("defend");
link2event.onclick = defend;
function defend() {
alert("working now");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="console">
<p id="startGameMessage"></p>
<div id="gameArea">
<p id="gameMessage">Some Text</p>
link1
<div id="placeHolder"></div>
</div>
</div>

When you link up your attack onclick, the element exists. But because #defend does not exist on the dom when you run var link2event = document.getElementById("defend");, your onclick never gets set.
Instead try:
var getupvar = document.getElementById("attack");
getupvar.onclick = attack;
function attack(){
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
var link2event = document.getElementById("defend");
link2event.onclick= defend;
}
function defend(){
alert("working now");
}
jsfiddle https://jsfiddle.net/fv9mpbm6/
This will get your code working how you wish. If you don't do so, your code cannot work because the two lines added to the attack() function will be executed when you call the .js file in your html document as a script and not as a function. This means that the method getElementById("defend") will not find anything, because when you initialize the page, you cannot find any element with this id, you create it when you click on the link.
But do note that if you click attack more than once, your code will break because there will be more than one defend element.

When creating dynamic content, never use ids for handlers! Use classes instead
function attack() {
$('link2').insertBefore("#placeHolder");
}
Also, to ensure proper handling for elements that may not exist yet, leverage jquery's on functionality
$('body').on('click', '.defend', function() {
alert("working now")
})

it is simple, just put the two lines of code
var link2event = document.getElementById("defend");
link2event.onclick= defend;
inside the attack() function, at the end,and it works. This is the new attack() function:
function attack(){
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
var link2event = document.getElementById("defend");
link2event.onclick= defend;}
If you don't do so this code cannot works because these two lines will be executed when you call the .js file in your html document as a script and not as a function. This means that the method getElementById("defend") will not find nothing, because when you initialize the page, you cannot find any element with this id, you create it when you click on the link.
I hope that this helps!
Cheers!

Try this, I am not sure is this what you expect
var getupvar = document.getElementById("attack"), i=0;
getupvar.onclick = attack;
function attack() {
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
var link2event = document.getElementById("defend"+i);
link2event.onclick = defend;
i++;
}
function defend() {
alert("working now");
}

Related

Changing image SRC using javascript - unknown error

I'm using javascript for the first time and am having difficulty getting certain features to work. Crucially I can't seem to get the following line of code to execute.
document.getElementByID("reportImage").src=filepath;
The full code is given below.
Notice that I've created a test function to try and narrow down the cause of the malfunction. The first two functions are there to demonstrate intent but are not currently being called by the .
The behavior of the test function suggests that the error is within this specific line. Notably the alert will fire if it is placed first in the function but will not trigger if placed second (suggesting that this specific line is problematic in some way).
It may be a simple syntax error but I've checked many times and can't see what it might be. Please help!
<!DOCTYPE html>
<html>
<script>
/* declare and set script variables */
var numberOfImages, imageArray, timing, containingFolder, i;
i = -1;
timing = 3;
containingFolder = "H:\\Images";
imageArray = [
"FoxKey.jpg",
"TeamKPI2.tif"
]; //imageArray should contain names of image files that sit within the specified folder
numberOfImages = imageArray.length;
function activateImageTimer() {
/* function iterates through selected images */
if (numberOfImages === timingArray.length) {
setInterval(nextImage(), timing*10);
}
else { alert("Please check contents of imageArray and timingArray. The
number of images should correspond to the number of timings."); }
}
function nextImage() {
i = (i+1) % numberOfImages; //use modulus function to loop through array
var filepath = containingFolder + "\\" + imageArray[i]; //build filepath
document.getElementByID("reportImage").src=filepath;
}
function testFunction() {
document.getElementByID("reportImage").src="H:\\Images\\FoxKey.jpg";
alert("Function is functioning");
}
</script>
<body onload="testFunction()">
<img id="reportImage" src="H:\Images\TeamKPI2.tif">
</body>
</html>
JavaScript is Case Sensitive.
Try with this:
Change: document.getElementByID to document.getElementById
And, <script></script> it has to be put inside the body or head, not of html.

HTML showing the code as text instead of doing the function

I'm new to making websites, only got some notions of C++. So I have this code
in HTML:
<html>
<body>
<script type="text/javascript" src="http://localhost/Coin/wp-content/uploads/custom-css-js/77.js "></script>
<p>Click the button to trigger a function ".</p>
<button onclick="myFunction()">Generate question</button>
<p id="demo"></p>
<div id="quote"></div>
<script>
function myFunction()
{
document.getElementById("quote").innerHTML = showquote;
}
</script>
</body>
</html>
And this in JavaScript:
var myArray = ['Question 1', 'Test2', 'Practise 3'];
var rand = Math.floor(Math.random() * myArray.length);
function showquote(){
document.getElementById('quote').innerHTML = myArray[rand];
}
showquote();
When the button is clicked, this line appears:
function showquote(){ document.getElementById('quote').innerHTML = myArray[rand]; }
As I said, I'm just trying things in this languaje I barely know about, am I not invoking the function right? Thanks in advance.
function myFunction()
{
document.getElementById("quote").innerHTML = showquote;
}
should be
function myFunction()
{
showquote();
}
Click here for an executable demo of the solution above.
Reasoning
When you do
document.getElementById("quote").innerHTML = showquote;
You are assigning to the inner HTML the source code of the showquote function. Which is why you get function showquote(){ document.getElementById('quote').innerHTML = myArray[rand]; } (the source code of showquote) shown in the page.
So, what you really want to do is just call the showquote function, because that function alters the HTML alone. Thus the correct expression being showquote(), which invokes the showcode function.
Other improvements
Since now your myFunction is just a call to showquote:
function myFunction()
{
showquote();
}
Then you could actually remove it and use showquote directly in the HTML element.
<button onclick="showquote()">Generate question</button>
Another thing is, inside your JavaScript file, your first invocation of showquote, right after its declaration, in here:
function showquote() {
document.getElementById('quote').innerHTML = myArray[rand];
}
showquote(); // <----- this is the invocation I'm talking about
Is goint to yield an error. Simply because its code tries to find the element with id = quote (here: document.getElementById('quote')) and at the point this JavaScript code is executing, such element does not exist yet. Thus you getting an error at that point.
The solution is here is maybe just not call showquote at all. Or call it in a <script> tag right near the bottom of the HTML page, somewhere after the quote element is declared.

Uncaught TypeError: google.script.run. is not a function

I have a code associated with a Google Spreadsheet, accessible via the script editor. In the code, I have a .gs file as the main body and I have an HTML file which is a sidebar used in the spreadsheet. I'm trying to call a function in the sheet.gs file from the HTML editor, would I do this using google.script.run.myFunction() in the HTML File, am I doing this wrong?
Basically in my sheet.gs I have
function myFunction() {
// do a thing
}
and in my HTML file I'm trying to call myFunction() like google.script.run.myFunction().
I have this function that is called by a button click
<div class="btn" onclick="generateSpreadsheetReport()">View Responses</div>
and the function is
function generateSpreadsheetReport() {
console.log("RUN!");
console.log("StudentAverage1");
var day = document.getElementById("day");
if (!day.value) day.value = "";
var course = document.getElementById("courses");
var stud = document.getElementById("stud");
console.log(day.value,course.value,stud.value)
google.script.run.withSuccessHandler(displayAverage).sortByParameter(day.value||"", course.value||"", stud.value||"");
console.log("StudentAverage2");
google.script.run.getStudentAverage(); // <----- This line right here isn't working.
}
And then in my sheet.gs I have a function called getStudentAverage() which is defined and it shows up in the library when I click on it from the resources page. So I Assume I am calling it wrong in my HTML
Not sure what your problem is, but from the looks of it in your sheet.gs try changing your
myFunction() {
// do a thing
}
to
function myFunction() {
return true;
}
It's just a wild guess based on the problem you've explained. Try this and let us know if it works for you.
Update: from your HTML file invoke myFunction() like
function myFunction() {
return true;
}
google.script.run.withSuccessHandler(function(myparam){
console.log("Response: "+myparam);
}).myFunction();

is there any way to print a javascript result into the div where the javascript function is being called?

I am wondering if is possible to do this.
I have my javascript function
function doSomething(){
return "Hello World"; //its actually more complicated method but the logic is the same..
}
so, at my html I have this.
<div class="someClass">
<script type="text/javascript">
doSomething();
</script>
</div>
So, basically, I want to is to print that hello world inside the div where is called.
Any idea how to do this?
AFAIK JavaScript cannot easily determine the location of its script declaration. As Marc B suggested in a comment--it works for printing to the document stream, but other applications won't work. Not to mention if you want the same behavior in multiple places, you've violated the "don't repeat yourself" (DRY) principle. You should instead inspect the dom document and find the element you wish to print "hello" in. This is easily accomplished with jQuery:
$(document).ready(function () {
$('.someClass').text('hello');
});
As laugri suggests, you should add an id to your div if you want only the one div changed.
<div id="someId".../>
...
$(document).ready(function () {
$('#someId').text('hello');
});
You can generate a unique div to find wherever you're code is executing
http://jsfiddle.net/190p77wu/
var doSomething = function (id) {
var targ = document.getElementById(id).parentNode;
targ.innerHTML = "This was inserted for id " + id;
}
and your html:
<div>
You shouldn't see this text.
<script>
var uniqueId = "tmp_" + Math.round(Math.random() * 100000000);
document.write('<div id="' + uniqueId + '"></div>');
doSomething(uniqueId);
</script>
</div>
Edit: or even cooler, if you have a properly cached JS file, you can do something like this:
http://jsfiddle.net/190p77wu/1/
var doSomething = function (script) {
var targ = script.parentNode;
targ.innerHTML = "This was inserted dynamically";
}
and this html:
<div>
You shouldn't see this text.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" onload="doSomething(this)"></script>
</div>
Try setting an id at script element , calling script.parentElement within doSomething
<div class="someClass">
<script type="text/javascript" id="someClass">
function doSomething() {
var elem = document.getElementById("someClass");
elem.parentElement.appendChild(
document.createTextNode("Hello World")
)
}
doSomething();
</script>
</div>

Using script variables in html body

I want to call the variable from the script to body.
Here is my script code. I want to take the rightanswers and wronganswers values to use in html body.
GetFeedback = function (a) {
if (a == CorrectAnswer) {
rightanswers++;
} else {
wronganswers++;
}
lock = true;
}
You need to use the Document Object Modle. You have different methods with JavaScript to create and insert elements into the DOM. As for example:
var element = document.createElement('p');
var body = document.body;
body.appendChild(element);
With that code you are creating an element, then appendig it into the body. And that is pure JavaScript. You could use Mootools or jQuery, and It is goign to be simpler. But JavaScript doesn't work like PHP for example, where you can use the variables mixed up with the HTML.
And if you want to trigger the function from the HTML you need to bind thtat function to an event. For example clicking on a link would be.
HTML
Click Here
JS
var b = document.getElementById('button');
b.click = function(){
GetFeedback();
}
Make sure you're declaring the variable (we can't see that in the code provided) by using var:
<script>
var GetFeedback = function (a) {
if (a == CorrectAnswer) {
rightanswers++;
} else {
wronganswers++;
}
lock = true;
</script>
Then in your HTML, you can use feedback like this (although, it's not good practice to use the below, it's merely for demonstration purposes):
Hello
you can use jquery to change the html on the page.
GetFeedback = function(a){
if(a==CorrectAnswer){
rightanswers++;
}else{
wronganswers++;
}
lock=true;
$('p:first').html('Right Answers: '+rightanswers+' <br> Wrong Answers: '+wronganswers);
};
and have this as your html
<body>
<p></p>
Get Feedback
</body>

Categories