I want to ask, how to make this script directly display the total of numbers on my blog post without clicked, And will change if browser is refreshed.
` http://jsfiddle.net/BenedictLewis/xmPgR/
There the problem is, your getNumber() function is executing only after click. There is no way it is not added to on load part.
One simple way is call the function getNumbers() after declaration as i did:
var link = document.getElementById('getNumber'); // Gets the link
link.onclick = getNumber; // Runs the function on click
function getNumber() {
var minNumber = 0; // The minimum number you want
var maxNumber = 100; // The maximum number you want
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
$('#myNumber').html(randomnumber); // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
getNumber(); // here i called the method, it runs on load of the script
//and works as you wanted
Related
I have these set of 11 numbers that increase per second, but I want each increment or the current set of numbers to write on a new line. E.g;
20220215155
20220215156
20220215157 etc...
I tried adding the n tag buh it returned an error.
var i = 20220215155
function increment() {
i+, + </n>;
document.getElementById('test').innerHTML = i
}
('increment()', 1000);
Please I really need help as I have been trying to get this for so long.
Your code is not valid JS
Here is something that does work - I am using setInterval here
var i = 20220215155
function increment() {
i++; // increment
document.getElementById('test').innerHTML += i + "<br/>"; // add it with a breakline
}
setInterval(increment, 1000);
<div id="test"></div>
You can use a template literal for the string too
`${i}<br/>`
You can use setTimeout to call the function after a set time while also increasing the number you initially pass into the function.
// Cache the element
const test = document.querySelector('#test');
let n = 20220215155;
// `increment` accepts `n` as an argument
function increment(n) {
// Add a new HTML string to the element
test.innerHTML += `${n}</br>`;
// Call the function again with an new `n`
setTimeout(increment, 1000, ++n);
}
increment(n);
<div id="test"></div>
Additional documentation
Template/string literals
Hello everyone and thanks for any help in advance,
I have some functions already in place, first one adds 1% of the total money amount once every second. the second is onclick there is $100 added to the total original amount. The third is to minus $200 plus 10% of the 200 from the total amount, so every time it is clicked the minus amount goes up.
These functions are working on my local machine but I am unable to get them to work in a JSFIDDLE.
I want to disable the minus button once the total amount is less than the minus amount, and also enable it again once there is enough money in the total amount to use.
Here is my JS so far
setInterval(function () {
var moneyTotal = document.getElementById('money-total').innerHTML;
var perSec = (1 / 100) * moneyTotal;
var moneyNewTotal = (+moneyTotal) + (+perSec);
document.getElementById('money-total').innerHTML = (moneyNewTotal.toFixed(2));
document.getElementById('per-second').innerHTML = (perSec.toFixed(2));
}, 1000);
function add() {
var addAmount = 100;
var moneyTotal = document.getElementById('money-total').innerHTML;
var addTotal = (+addAmount) + (+moneyTotal);
document.getElementById('money-total').innerHTML = (addTotal.toFixed(2));
}
function minus() {
var cost = document.getElementById('cost').innerHTML;
var money = document.getElementById('money-total').innerHTML;
if (money > cost) {
var moneyNewTotal = (+money) - (+cost);
var newCost = (10 / 100) * cost;
var costTotal = (+newCost) + (+cost);
document.getElementById('cost').innerHTML = Math.ceil(costTotal);
document.getElementById('money-total').innerHTML = (moneyNewTotal.toFixed(2));
} else {
alert("Not enough money");
}
}
Any help would be greatly appreciated!
First, the Fiddle isn't working because you have it set to load your javascript onLoad which is wrapping your functions in a different scope and so they aren't available on the window. Changing it to load the javascript No wrap - in <head> (or <body>) will help it work.
Then you need to have something that is checking for the value and enabling disabling the minus button.
function checkTotal() {
var moneyTotal = +document.getElementById('money-total').innerHTML;
var cost = +document.getElementById('cost').innerHTML;
if (cost > moneyTotal) {
document.getElementById('minus').setAttribute('disabled', 'disabled');
} else {
document.getElementById('minus').removeAttribute('disabled');
}
}
Then you would need to call this at the end of the add, minus, and even the function you have defined in setInterval so that as money gets added it checks. This code only adds the disabled attribute to the button, so any styling would need to be handled either by the code or through CSS and setting/removing class names or something similar.
There are perhaps different ways to do this through data binding or using an event model as part of a framework, but those are a more substantial topic that can't really be covered in this answer.
I have a function draw_integer(n,s,x,y,plotx) , which draws a integer ,n on HTML5 canvas of size s in the coordinates (x,y), I am calling this function inside another function draw_num() as follows,
(plot0, number and size are the respective id's of canvas, number & size input fields,
function drawnum() is being triggered with an onclick event.)
function drawnum() {
var n = document.getElementById('number').value;
var s = document.getElementById('size').value;
console.debug(n,s);
draw_integer(n,s,100,100,plot0); // this doesn't get executed
}
function draw_integer(n,s,x,y,plotx){ //lots of code }
The draw_integer function being called under drawnum doesnt get executed, what is the problem I am unable to identify.
using console.debug() returns the appropriate values of number and size as entered by user, also if i use draw_integer(3,100,100,100,plot0) (draw number 3 of size 100) instead of draw_integer(n,s,100,100,plot0) it works .
So that means that there is some error occuring while passing the varaible n and s from drawnum() to draw_integer().
Thinking that this might be due to to the local scope of the variables , I tried this.
var n = document.getElementById('number').value;
var s = document.getElementById('size').value;
function drawnum() {
console.debug(n,s);
draw_integer(n,s,100,100,plot0); // this doesn't get executed
}
function draw_integer(n,s,x,y,plotx){ //lots of code }
But that didn't work either.
can you help me out or suggest a better way to solve this problem .
var n = document.getElementById('number').value;
var s = document.getElementById('size').value;
The variables n and s above are Strings and not Numbers. You need to either use parseFloat or parseInt to convert it.
var n = parseInt(document.getElementById('number').value, 10);
var s = parseInt(document.getElementById('size').value, 10);
I have a book on my page consist of 3 iframes, 1 iframe opens the table of contents and 2 iframes to open 2 pages at the same time, also i have 2 buttons to navigate pages next and previous through this function
var pNum = 1;
var pNum2 = 2;
var maxPage = 108;
pNum = pNum+2;
pNum2 = pNum2+2;
if (pNum > maxPage) {pNum=1;pNum2=2;}
document.getElementById("Frame_C").src="page"+pNum+".jpg";
document.getElementById("Frame_B").src="page"+pNum2+".jpg";
}
function prev(){
pNum = pNum-2;
pNum2 = pNum2-2;
if (pNum < 1) {pNum=107;pNum2=108;}
document.getElementById("Frame_C").src="page"+pNum+".jpg";
document.getElementById("Frame_B").src="page"+pNum2+".jpg";
}
if I click on link in table of contents it open 2 pages with this link
<td>
<p class=Mmenu>
whatever
</td>
the problem starts here, if i click on next-previous button I want it to continue from page 36,37 but what happens it continue from pNum in the function, how to update the pNum from onclick ? or maybe another solution !!
You are encountering troubles because your "whatever" link is changing the state that your prev() function is expecting to be not-messed-with.
When one has some kind of state (e.g. some variables representing a book with pages), it is important to not violate the representation invariants or internal representation. Thus
Everything that touches the book should keep its internal state consistent.
A good way to code such that this is the case is to create a bunch of special interfacing functions that make sure the state is consistent (demonstrated below via a single function gotoPage which makes sure everything is kept tidy; one could use more than a single function, but they would each need to keep things tidy).
First one has to come up with the rules you want for the internal state. In the example below, the rule is "rightPage is always equal to leftPage+1, and the iframes always show leftPage.jpg and rightPage.jpg, except if it's an invalid page, in which case that iframe shows an about:blank".
Try this:
function $id(id) {
return document.getElementById(id);
}
/*
internal representation
these values changed only by the gotoPage function
invariant:
- rightPage is always equal to leftPage+1
- iframes always show leftPage.jpg and rightPage.jpg,
except if it's an invalid page, in which case that
iframe shows an about:blank
*/
var leftPage = 0; // page0 is blank
var rightPage = 1; // must always be equal to leftPage+1; which may be an invalid page
var PAGE_MAX = ???;
function gotoPage(num) {
if (num<0)
num = 0;
if (num>PAGE_MAX)
num = PAGE_MAX; // may need to think about this some more
// most books seem to put even pages on left and odd on right
function isEven(n) {
return n%2==0; // sidenote: abs(n%2)==1 -> odd
}
leftPage = isEven(num) ? num : num-1;
rightPage = leftPage+1;
updateDisplay();
}
function prev() {
gotoPage(leftPage-2);
}
function next() {
gotoPage(leftPage+2);
}
function gotoPageByGuess(elem) {
var pageNum = parseInt(elem.innerHTML.slice(-2));
gotoPage(pageNum);
}
function updateDisplay() {
// using jquery
$id('leftPage').src = 'page'+leftPage+'.jpg';
if (rightPage <= PAGE_MAX)
$id('rightPage').src = 'page'+rightPage+'.jpg';
else
$id('rightPage').src = 'about:blank';
}
Then don't use a regular href or target, but just do:
<a onclick="prev()">Previous</a>
<a onclick="next()">Next</a>
Then you can do either of these, depending on which is easiest:
<a onclick="gotoPage(26)">Chapter 2: Some Title......... p26</a>
<a onclick="gotoPageByGuess(this)">Chapter 2: Some Title......... p26</a>
edit: removed with(Math){...} statement, which allows you to use math functions like abs() without verbosely calling Math.abs()
This on e is a doozey.
I have while loop to generate a random number that is not the same as any other random number produced before. The random number is used to select a text value from an object.
for example:
quoteArray[1] = "some text"
quoteArray[2] = "some different text"
quoteArray[3] = "text again"
quoteArray[4] = "completely different text"
quoteArray[5] = "ham sandwich"
This is part of a larger function and after that function has cycled through = quoteArray.length it resets and starts the cycle over again. The issue I am hitting is that the following code is SOMETIMES producing an infinite loop:
//Note: at this point in the function I have generated a random number once already and stored it in 'randomnumber'
//I use this while statement to evaluate 'randomnumber' until the condition of it NOT being a number that has already been used and NOT being the last number is met.
while(randomnumber === rotationArray[randomnumber] || randomnumber === lastnumber){
randomnumber = Math.floor(Math.random() * (quoteArray.length));
}
When I console.log(randomnumber) - when I am stuck in the loop - I am just getting '0' as a result. When stuck in the loop it doesn't appear as though Math.floor(Math.random() * (quoteArray.length)) is producing a random number but rather just '0' infinitely.
can anyone tell me why I am running into this problem?
EDIT: Here is the complete pertinent code with function + variable declarations
// Function to initialize the quoteObj
function quoteObj(text,cname,ccompany,url,height) {
this.text=text;
this.cname=cname;
this.ccompany=ccompany;
this.url=url;
this.height=height;
}
// Populate my quotes Object with the quotation information from the XML sheet.
var qObj = new quoteObj('','','','');
var quoteArray = new Array();
var counter = 0;
//cycles through each XML item and loads the data into an object which is then stored in an array
$.ajax({
type: "GET",
url: "quotes.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('quote').each(function(){
quoteArray[counter] = new quoteObj('','','','');
console.log(quoteArray[counter]);
quoteArray[counter].text = $(this).find('text').text();
quoteArray[counter].cname = $(this).find('customer_name').text();
quoteArray[counter].ccompany = $(this).find('customer_company').text();
quoteArray[counter].url = $(this).find('project').text();
++counter;
});
}
});
// This is the setion that is generating my infinite loop issue.
// I've included all of the other code in case people are wondering specific things about how an item was initialized, etc.
// Generate a random first quote then randomly progress through the entire set and start all over.
var randomnumber = Math.floor(Math.random() * (quoteArray.length));
var rotationArray = new Array(quoteArray.length);
var v = 0;
var lastnumber = -1;
bHeight = $('#rightbox').height() + 50;
var cHeight = 0;
var divtoanim = $('#customerquotes').parent();
//NOT RELATED//
// Give the innershadow a height so that overflow hidden works with the quotations.
$(divtoanim).css({'height' : bHeight});
// Rotate the Quotations Randomly function.
setInterval(function(){
randomnumber = Math.floor(Math.random() * (quoteArray.length));
//checks to see if the function loop needs to start at the beginning.
if(v == (quoteArray.length)){
rotationArray.length = 0;
v = 0;
}
//determines if the random number is both different than any other random number generated before and that is is not the same as the last random number
while(randomnumber === rotationArray[randomnumber] || randomnumber === lastnumber){
randomnumber = Math.floor(Math.random() * (quoteArray.length));
}
lastnumber = randomnumber;
rotationArray[randomnumber] = randomnumber;
++v;
//NOT RELATED//
//animation sequence
$('#ctext, #cname').animate({'opacity':'0'},2000, function(){
$('#ctext').html(quoteArray[randomnumber].text);
$('#cname').html('- ' + quoteArray[randomnumber].cname);
cHeight = $('#customerquotes').height() + 50;
adjustHeight(bHeight,cHeight,divtoanim);
$('#ctext').delay(500).animate({'opacity':'1'},500);
$('#cname').delay(1500).animate({'opacity':'1'},500);
});
},15000);
This is an asynchronous problem: the array quoteArray is empty when the code runs, because it fires off the ajax request, and moves on. Anything that depends on quoteArray should be inside the success function of $.ajax.
The array has a length when you type quoteArray.length in the console, only because by that time the Ajax request has completed.
have you tried something like
Math.floor(Math.random() * (5));
To make sure the array length is being found properly?
First, since you updated your question, be sure that you are handling asynchronous data properly. Since an ajax call is asynchronous, you will need to be sure to only run the randomizer once the call is successful and data has been returned.
Second, assuming you are handling the asyc data properly, the size of your result set is likely it is too small. Thus, you are probably randomly getting the same number too often. Then, you can't use this number because you have already done so.
What you need to do is pop off the parts that are already used from the results array each time. Recalculate the array length, then pull a random from that. However, the likelihood of this feeling random is very slim.
There is probably a more efficient way to do this, but here's my go:
var results = ['some text','some text2','some text3','some text4','some text5', /* ...etc */ ],
randomable = results;
function getRandomOffset( arr )
{
var offset,
len;
if( arr.length < 1 )
return false;
else if( arr.length > 1 )
offset = Math.floor(Math.random() * arr.length );
else
offset = 0;
arr.splice( offset, 1 );
return [
offset,
arr
];
}
while( res = getRandomOffset( randomable ) )
{
// Set the randomable for next time
randomable = res[1];
// Do something with your resulting index
results[ res[0] ];
}
The arrgument sent to the function should be the array that is returned form it (except the first time). Then call that function as you need until it returns false.