Why is my javascript code going into an infinite loop? - javascript

In the code below, whenever I click on the submit button, multiple window's open up as it it were in infinite loop. If I uncomment alert, then multiple alerts keep popping like they were in infinite loop. Why could this be happening ?
<html>
<head>
<script type = "text/javascript">
var window;
function moveBy() {
//alert("-- hello ---");
window = window.open("http://www.w3schools.com");
window.moveBy(10, 20);
}
</script>
</head>
<body>
<input type = "submit" value = "moveBy" onclick = "moveBy()"> </input>
</body>
</html>

Javascript does not support method overloading, so by calling window.moveBy(10, 20); you are actually basically calling moveBy() again, resulting in an infinite loop.
Calling a function from itself is called recursion. The linked post is a good read on this topic, and will guide you on where you might want it. But in your case you clearly don't.
Have a read of this article for more detail.
To prevent this from happening, you can rename your moveBy() function to myMoveBy() or better openAndMoveBy()

Because you call function moveBy from itself.

You are creating a recursion (function that calls itself) by calling window.moveBy inside your moveBy function without stating a break point or exit case:
function moveBy() {
//alert("-- hello ---");
window = window.open("http://www.w3schools.com");
window.moveBy(10, 20); //recursion, it will call this function over and over again.
}
Maybe what you want is to use another name for your function and call the actual window.moveBy inside with predefined parameters:
function customMoveBy() {
//alert("-- hello ---");
window = window.open("http://www.w3schools.com");
window.moveBy(10, 20);
}
<input type = "submit" value = "moveBy" onclick = "customMoveBy()"> </input>

The problem is that you are calling the function moveBy inside the funtion moveBy. Whenever you execute the function you call it again and again ...
Try this:
<html>
<head>
<script type = "text/javascript">
var window;
function moveBy() {
alert("-- hello ---");
window = window.open("http://www.w3schools.com");
//window.moveBy(10, 20);
}
</script>
</head>
<body>
<input type = "submit" value = "moveBy" onclick = "moveBy()"> </input>
</body>
</html>

Related

javascript onclick to display time and date in a paragraph or not

I'm trying to get the date to appear in an empty paragraph with an ID when I click on a button. So far no luck. Don't mind if I cant get it to appear in the paragraph but just want to know how to make it appear when I click the button thanks in advance.
sorry if its a dumb one,
I have got the alert working on click but just can not seem to figure this one out
<!DOCTYPE html>
<html>
<head>
<title>Lets Practice Some Code</title>
<link rel="stylesheet" type="text/css" href="/Users/Matteveli/Desktop/javascript practice/style/style.css">
</head>
<body>
<div><h1 id="topTitle"> Time and date Test</h1></div>
<div><button id="alerter">click Me to make an alert pop up.</button></div>
<p id="empty"
></p><div><button id="timeAndDate">click Me to display time and date</button></div>
<script type="text/javascript" src="/Users/Matteveli/Desktop/javascript practice/javascript/funtionality.js"></script>
</body>
<footer>
</footer>
</html>
var alerterButton = document.getElementById("alerter");
var dateButton = document.getElementById("timeAndDate");
var emptyP = document.getElementById("empty");
var d = new Date();
// for the first click that we have working.... " THE ALERT "
//a link to function was called then the function was made
// as below
alerterButton.onclick = myClickHandler;
function myClickHandler() {alert("the document was clicked")};
/// TIME AND DATE ???
dateButton.onclick = emptyP.innerHTML=d;
function showMeTheDate() {emptyP.innerHTML+d};
any help greatly appreciated.
thanks in advance.
Here an example: http://jsfiddle.net/sckjnx7t/2/
The key is engage function and event, in this case onclick, then, you could do:
dateButton.onclick = function(){
//code here
};
or:
dateButton.onclick = showMeTheDate();
function showMeTheDate() {
//code
};
dateButton.onclick should be a function. So, you should do
dateButton.onclick = () => { emptyP.innerHTML= d.getDate() }
Only edit your event handler function, and set pharagraph's innerHTML to d.getDate().
function myClickHandler() {
alert("button was clicked!");
emptyP.innerHTML = d.getDate();
}
You need to stay the function workers in same scope. Without this approach, the latest eventHandler function will be used for all time, because other (last) functions' functionality won't be.

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.

Calling javascript function in html second time

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");
}

Javascript Calculation function - Not calculating in html

I am having an issue implementing this calculator on my website which i created. I think i have used the wrong javascript to create the simple calculation which is the following math calculation: ((list price - rrp) / list price) * 100
PLEASE NOTE, i am aware of the values not being numbers, please replace them with any numbers. it still doesnt work.
This is to get the percentage value of the discount against the list and the RRP.
Please review the code before HTML:
<script type="text/javascript">
discountFinal(#OriginalPrice, #ListPrice);
</script>
<div id="discountCode">
<span id="spanish"></span>
<span id="spanishtwo">%</span>
</div>
Javascript:
var discountFinal = function (firstly, secondly) {
var totalfirst = secondly - firstly;
var totalsecond = totalfirst / secondly;
var totalthird = totalsecond * 100;
if (document.getElementById("discountCode").innerHTML === null) {
document.getElementById("spanishtwo").innerHTML.replace("%", "")
} else {
document.getElementById("spanish").innerHTML = Math.floor(totalthird / 5) * 5
}
};
I dont think i am calling the function within the html properly. Can someone assist with this please.
http://jsfiddle.net/xwzhY/
I'm not sure the error you're getting, but it seems as if you're calling the discountFinal function before it's defined. When you move the call, it starts to work:
http://jsfiddle.net/bmonty/xwzhY/4/
Edit after comment from OP.
You just need to make sure your discountFinal function is defined at the top of your page, before any place it gets called.
This will work:
<script type="text/javascript">
var discountFinal = function(a, b){};
</script>
<script type="text/javascript">
var result = discountFinal(1, 2);
</script>
But this will throw an error:
<script type="text/javascript">
var result = discountFinal(1, 2);
</script>
<script type="text/javascript">
var discountFinal = function(a, b){};
</script>
To get some clarification, View Source on the HTML page from your browser to see what the resulting page looks like. That should point out where the order of operations is getting messed up.
It works fine if you call your function after it exists: http://jsfiddle.net/xwzhY/2/
Just make sure that the function is declared earlier in the code than you use it. Or declare it using a function statement rather than a function expression assigned to a variable:
function discountFinal(firstly, secondly){
...
Trying put "" around your perl variable, you need to pass the value

Pass Variable to a Popup Window using Javascript

I need to pass some text from the current page to a popup window without going for a server hit. The information (herewith represented by 90) is already available in the parent form (it's like a paragraph-long text which is stored in a hidden variable). I just need to display that as a popup.
Here's what I've tried, this works to some extent but doesn't work if I pass text, instead of a number. My second concern is that the solution kinda looks ugly. Any tips? Thank you.
This is SCCE, you can run it straight in your machine.
<html>
<head>
<title>A New Window</title>
<script type="text/javascript">
var newWindow;
var data;
function makeNewWindow(param) {
data = param;
if (!newWindow || newWindow.closed) {
newWindow = window.open("","sub","status,height=200,width=300");
setTimeout("writeToWindow()", 50); /* wait a bit to give time for the window to be created */
} else if (newWindow.focus) {
newWindow.focus( ); /* means window is already open*/
}
}
function writeToWindow() {
var k = data;
alert(data);
var newContent = "<html><head><title>Additional Info</title></head>";
newContent += "<body><h1>Some Additional Info</h1>";
newContent += "<scr"+"ipt type='text/javascript' language='javascript'> var localVar; localVar = "+ k +"; document.write('localVar value: '+localVar);</scr"+"ipt>";
newContent += "</body></html>";
// write HTML to new window document
newWindow.document.write(newContent);
newWindow.document.close( ); // close layout stream
}
</script>
</head>
<body>
<form>
<input type="button" value="Create New Window" onclick="makeNewWindow('90');" />
</form>
</body>
</html>
Actually, I googled and saw some other approach that uses window.opener.document.forms.element, but here, the window has to know in advance what it has to read from the parent. I need to be able to pass it as it will vary:
<textarea rows="15" name="projectcontent" id="projectcontent" cols="87"></textarea>
<b>View Content</b>
<head>
<title>View Project Content</title>
</head>
<body>
<img src="/images/toplogo.jpg"><br/>
<script language="Javascript">
document.write(window.opener.document.forms['yourformname'].elements['projectcontent'].value)
</script>
<img src="/images/bottomlogo.jpg">
</body>
</html>
use window.opener
From Mozilla Developer Network:
When a window is opened from another window, it maintains a reference
to that first window as window.opener. If the current window has no
opener, this method returns NULL.
https://developer.mozilla.org/en-US/docs/Web/API/window.opener
This way you can have on your original window a callback, and you can notify the window it's load and ready, rather than wait a random delay...
you add a function on the original window:
window.popupReady = function (callbackToPopup) {
callbackToPopup(newData);
}
then the popup can tell the parent window it's ready and pass it a callback to update it with data..
and on the popup try something like:
window.dataReady(newData)
{
alert(newData);
}
document.addEventListener("load", function() { window.opener.popupReady (dataReady); }
I didn't test this code, but I would take such a path as this should ensure the popupWindow is ready for you and is along the spirit of JavaScript.
In your onclick attribute you pass '90' to the function, but the function isn't set up to take an argument. So, change the first line of your function like this:
function writeToWindow(data) {
You don't need the global var data; or the local var k = data;, so get rid of them.
And instead of + k + write + data +.
That should do get your data passed.
Use this code, it works perfectly in all browsers .
#desc = parent text area id
#desc_textarea = popup
$("#desc_textarea").val(window.opener.$("#desc").val())

Categories