Two different ways of function calling in JavaScript [duplicate] - javascript

This question already has answers here:
Setting a variable equal to a function without parenthesis? [duplicate]
(3 answers)
Closed 8 years ago.
In the following code, once I run it, it waits for click event to fire an alert. However if I change the following javascript code
from
clickMeButton.onclick=runTheExample;
to
clickMeButton.onclick=runTheExample();
it always fires up an alert when page downloaded without any click event. I would like to know what is the difference. I am using Chrome. Snipped code is as follows:
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
<script type="text/javascript" src="script13.js"> </script>
</head>
<body>
<h1 id="title">DOM Example </h1>
<p id="first">This is the first paragraph</p>
<p id="second"><strong>This is the second paragraph</strong></p>
<p id="third">This is the third paragraph</p>
<input type ="text" id="myTextBox" />
<input type ="submit" id="clickMe" value="Click Me!"/>
Google!
</body>
</html>
//script13.js
window.onload= function(){
var clickMeButton=document.getElementById('clickMe');
clickMeButton.onclick=runTheExample;
}
function runTheExample(){
alert('running the example');
}

var x = func(); //Means you execute the function and output its return value to x;
var x = func; //Means you attribute the function to the variable, so you can call it, using x.
Example
function f(){
return 4;
}
var x = f(); // x = 4
var x = f; // x = f()

Related

JavaScript Function works in body but not in Head

I am learning JS as part of my studies and at the moment I am trying some examples from W3Schools and am stuck on JS Functions page. The link of the page is:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_function_return
If I use the example code them the code runs perfectly just as below code:
<html>
<head>
</head>
<body>
<p id="demo"> </p>
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(3, 4);
</script>
</body>
</html>
But if I take the script portion of the above code inside Head tags just like below code then the function does not execute at all and I do not get any value:
<html>
<head>
<script>
function myFunction(a, b) {
return a * b;
document.getElementById("demo").innerHTML = myFunction(3, 4);
}
</script>
</head>
<body>
<p id="demo"> </p>
<button type="button" onclick="myFunction()">Click me</button>
</body>
</html>
Can someone point me where I am doing wrong and how to fix this issue.
Cheers,
Your code has a couple issues. Here's how to fix it:
First off, you functions return a value at the end of the function, after processing parameters. Having a return at the beginning is bad.
Second, you've got to call the function with arguments from the onclick HTML attribute. Right now, there's nothing in the function call myFunction(). It should look like myFunction(3, 4).
Lastly, what was the point of calling myFunction() within the function declaration? That doesn't make sense.
I've adjusted your code with comments to help you make sense of it. This should be helpful.
<html>
<head>
<script>
function myFunction(a, b) {
// Return is usually the last thing you do in a function.
// Also, don't call a function from within the function.
// Instead, put what you had in return in the demo element's innerHTML.
return document.getElementById("demo").innerHTML = a * b; // a * b,
// not 3 * 4.
}
</script>
</head>
<body>
<p id="demo"> </p>
<!-- Also, there were no arguments here. You need to specify arguments in
the onclick event -->
<button type="button" onclick="myFunction(3, 4)">Click me</button>
</body>
</html>
I hope this is helpful!
When you are calling myFunction in the click handler you are not passing any parameters to it, also the first statement in it is a return statement which means the second param will not get executed.
What you need to do is to define the function such a way that it will take 2 parameters then will multiply them and put the result to #demo element.
Then on click of the button, you can call the function with the desired parameters
<html>
<head>
<script>
function myFunction(a , b) {
document.getElementById("demo").innerHTML = a * b;
}
</script>
</head>
<body>
<p id = "demo"> </p>
<button type="button" onclick = "myFunction(3, 4)">Click me</button>
</body>
</html>
There are significant errors in this function definition:
function myFunction(a , b) {
return a * b;
document.getElementById("demo").innerHTML = myFunction(3, 4);
}
First, you call it using myFunction(), which assigns both a and b the value undefined; when you multiply them, you get NaN, which you return. When you return from a function, nothing else in the function gets executed. And if you didn't return, you would get into an infinite recursive loop (which would probably end in a stack overflow) as you keep calling the function from itself again and again.
These errors are the reason the script is not working; nothing to do with it being in the head.
Because you had return in myFunction and
document.getElementById("demo").innerHTML = myFunction(3, 4);
not executed. You could change into like this
<head>
<script>
function myFunction(a , b) {
return a * b;
}
function buttonClick() {
document.getElementById("demo").innerHTML = myFunction(3, 4);
}
</script>
</head>
<body>
<p id = "demo"> </p>
<button type="button" onclick = "buttonClick()">Click me</button>
</body>

Set value element to a other page called by window.open()

I'm struggling to implement this case, I really appreciate your help.
UPDATE :
page1.html
<html>
<head>
<title></title>
</head>
<body >
<form>
filled value : <input type="text" id="one">
</form>
</body>
</html>
page2.html
<form>
<input type="button" onclick='go();' value='call_page1'/>
</form>
First attempt : page1 shows up, but value is not set
<script>
function go(){
var newWindow;
newWindow= window.open('page1.html', 'form', 'width=400,height=350');
newWindow.document.getElemetById('one').value='xxx';
}
</script>
Second attempt : page1 is not even shown up
<script>
function go(){
var detailsWindow;
detailsWindow = window.open('page1.html', 'form', 'width=400,height=350');
detailsWindow.onload = function{
document.getElementById('one').value='test';
}
}
<script>
Question : setting value' value to page1.html, when it's called in page2.html?
Or if there's an alternative (but please take it easy on me, i'm just learning this stuff ). I don't use JQuery, if there's something unclear, i'm happy to hear it.
regard.
// page1.html
<script>
var newWindow = window.open('page2.html', 'formUntukUpdate', 'width=400,height=350');
newWindow.onload = function(){
newWindow.document.getElementById('one').value = 'ok 2';
};
</script>
// page2.html
<input type="text" id="one" value="ok" />
First of all javascript is case sensetive, and n is missing. so replace getElemetByID with getElementById.
Second is that the code executes immediately and doesn't wait the page to load. You must wrap your code in window.onload :
newWindow.onload = function(){
newWindow.document.getElementById('one').value='xxx';
}
there's 3 bugs in the update:
function in detailsWindow.onload = function must be declared with detailsWindow.onload = function() to work.
your end script is must be replaced from <script> to </script>
you are missing detailsWindow in document.getElementById('one').value = 'test'; it must be detailsWindow.document.getElementById('one').value = 'test';

How to display image using javascript

How to display an image as many times as input(number) given by the user in html using javascript? There seem to be an error in my code,dont know how to rectify.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag(c,x)">Try it</button>
<p id="demo"></p>
<script>
function imag(c,x) {
var x = document.getElementById("myNumber").value;
var c="<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr;
}
}
</script>
</body>
</html>
Try this:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag()">Try it</button>
<p id="demo"></p>
<script>
function imag() {
var x = document.getElementById("myNumber").value;
var c = '\<img src="http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2014/4/11/1397210130748/Spring-Lamb.-Image-shot-2-011.jpg"\/\>';
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr;
}
}
</script>
</body>
</html>
Notice that I just changed <button onclick="imag(c,x)">Try it</button> to <button onclick="imag()">Try it</button>; and I switched your apostrophes here: var c="<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
You told javascript that imag() should get two variables. but you never gave the function actual variables (and you filled them inside the function). so I removed the variables from the function's deceleration.
second thing I did was change the Quotation marks and Apostrophes since HTML standards require Quotation marks for the tags' content. switching between them allows you to keep the HTML standard.
The .innerHTML property takes a string. So, you need to convert your array to a single string like this:
document.getElementById("demo").innerHTML = arr.join("");
Note that 'C:/Users/Akhil/Desktop/New folder/G.jpg' is generally not a valid URL to refer to your image so you may need to fix that too. You can read here to see how file URLs work: http://en.wikipedia.org/wiki/File_URI_scheme
And, there's no reason to pass two empty variables to your imag() function. You can change this:
<button onclick="imag(c,x)">Try it</button>
to this:
<button onclick="imag()">Try it</button>
Firstly, you call imag function with the c and x, but the code doesn't know anything about them. That's why you get a TypeError.
You should create an event handler for the click event of the button, not this inline handler, where you can pass whatever you like at values of x and c.
Check this plunk here
And lastly, the innerHTML property takes a string (HTML or plain text). But in this case it will join all your values, comma separated, because the toString method of the array is invoked. Reference here
Your variables x and c are undefined, there is nothing in it so your code breaks. This is how parameters work, you give them a value and pass them to the function, so c becomes 'hello' and x becomes 5, fiddle:
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag('hello',5)">Try it</button>
<p id="demo"></p>
Javascript
function imag(c,x) {
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr;
}
}
But this is not very flexible right? So your solution is already stated in other answers. You don't pass in parameters and make the variables in the function everytime you click on the button and please stop using inline calls. It is really outdated, messy and unnecessary! Learn how to use eventhandlers.

Using data-* with javascript [duplicate]

This question already has answers here:
Access 'data-' attribute without jQuery
(5 answers)
Closed 8 years ago.
I am learning javascript and trying to store the value 2 in data-value in img element, and when I press the image I want to use javascript to show that value(2) in a paragraph. Here's my code:
<!DOCTYPE html>
<html>
<head>
<script>
function ispisi() {
var x = document.getElementById("myimage").data-value;
document.getElementById('demo').innerHTML = x;
}
</script>
</head>
<body>
<img id="myimage" data-value="2" onclick="ispisi()" src="bulboff.gif" width="100" height="180" />
<p id="demo">Text here<p>
</body>
</html>
The value should show in paragraph p, but when I click the image "text here" stays, insted. Why is this code not working?
try this
var x = document.getElementById("myimage").dataset.value;
OR
var x = document.getElementById("myimage").getAttribute("data-value");
The proper way to do this would be as follows:
function ispisi() {
var x = document.getElementById("myimage").getAttribute('data-value');
document.getElementById('demo').innerHTML = x;
}
window.onload = function() {
document.getElementById('myimage').onclick = ispisi;
};

Variable not sent to other function

I have a number of links, that when clicked on, passes a variable thru to another portion of the page.
Yet, for some reason, I can’t figure it out! What am I missing?
<head>
<script type="text/javascript">
function myFunction(a){
myid="Hi There!"+a;
return myid;
}
</script>
</head>
<body>
Click Me<br />
<script type="text/javascript">
document.write(myid);
</script>
</body>
You are getting a little mixed up here. Even though the function returns a value, it has nothing to return it to. Try this:
<head>
<script type="text/javascript">
function myFunction(a){
myid="Hi There!"+a;
document.getElementById("debug").innerHTML = myid;
}
</script>
</head>
<body>
Click Me<br />
<div id="debug"></div>
</body>
if you want to use it later you need to declare myid as a global variable. its scope is currently only within myFunction. also the document.write() function will only execute at runtime so you need to have another function the executes that with every click, or just combine the two.
When you click the link all that happens is that the myFunction() is called which returns the string. The line document.write(myid); is not executed anymore so nothing is visible.
<script>
// This is global
var myid = ''
myfunc = function(a){
myid = "Hi There!" + a;
alert(myid);
}
test_global = function(){
alert(myid);
}
</script>
Set MYID
<input type="button" onclick="test_global();" value="Test MYID" />
Here is a simple example of some similar stuff:
clickme or ClickMeAlso
<input id='other' type='text'/>
<script>
function myfunc(a) {
return a + " howdy";
};
</script>
You can see this in action here:http://jsfiddle.net/5Sbn2/

Categories

Resources