Javascript Reload Function - javascript

In my html website I have a random number function:
<script>
var randomnumber=Math.floor(Math.random()*11)
document.getElementById("random").innerHTML = randomnumber;
</script>
I would like to add a "reload" button that changes the random number generated, without reloading the page. Is there any way to do this besides the location reload?

Whenever you are going to repeat a process, you should use functions.
Your calculation is right. You just need to put it inside a function and call it in case of clicking the button.
function changeRandom(){
var randomnumber=Math.floor(Math.random()*11)
document.getElementById("random").innerHTML = randomnumber;
}
changeRandom();
<div id="random">
</div>
<button onclick='changeRandom()'>Click</button>

Related

How do you call a javascript function with a HTML button click?

So, I'm trying to make a dice roller that can, you guessed it!, roll dice. I want to call a javascript function within a HTML button click. I know this is very easy with angular, but I am not using Angular. I am using jQuery, but I don't want to make the whole thing jQuery, however, if I have to, I will. Anyway, I am trying to make a button that adds a die, one that removes a die, one that adds a side to the dice, and one that removes a side from the dice. Oh, and one that rolls the dice, but I've already coded that in.
Here's my HTML (note: I am using jQuery so it might look a little weird):
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
$("#button0").click(function(){
diceRoll = 0
for (i=diceAmt;i>0;i--) {
diceRoll += rand(1, diceSides)
}
document.getElementById("dieRoll").innerHTML = diceRoll;
})
</script>
</head>
<body>
<div class="screen">
<div class="top">
<div class="text">
<span id="dieRoll"></span>
</div>
<button class="button1" id="button0"></button>
</div>
<div class="bottom">
<button class="button2">Add die</button>
<button class="button3">Remove die</button>
<br/>
<button class="button2">Add side</button>
<button class="button3">Remove side</button>
</div>
</div>
</body>
</html>
Here's my JavaScript (again might look a little weird):
var diceAmt = 2
var diceSides = 6
var diceRoll
var xDx = diceAmt+"d"+diceSides
function floor(num){let n1=Math.round(num);let n2=n1-1;if(n1>num){return n2}else{return n1}}
function rand(num1,num2){let n1=num2+1-num1;let n2=floor(Math.random()*n1)+num2;return n2}
function addDie () {
diceAmt += 1
xDx = diceAmt+"d"+diceSides
document.getElementById("button0").innerHTML = "Roll "+xDx
}
function rmoveDie () {
diceAmt -= 1
xDx = diceAmt+"d"+diceSides
document.getElementById("button0").innerHTML = "Roll "+xDx
}
function addSide () {
diceSides += 1
xDx = diceAmt+"d"+diceSides
document.getElementById("button0").innerHTML = "Roll "+xDx
}
function rmoveSide () {
diceSides -= 1
xDx = diceAmt+"d"+diceSides
document.getElementById("button0").innerHTML = "Roll "+xDx
}
Now, I would normally show you my CSS here, but the CSS doesn't matter.
Oh, I almost forgot to show you the libraries I'm using. Here they are:
jquery.js
I would really like it if you could help me out here.
Thank you!
(Note: I would normally do that part in code but I figured it would be cooler if it was an actual h1.)
Whenever a button is triggered a click event is fired. To handle that event there are 3 ways in vanilla javascript:
1. Specifying the function to be called in an HTML tag.
<button class="button2" onclick="addDie()">Add die</button>
2. Adding a handler in the button onclick property in JS.
const button = document.getElementById("your_button_id");
button.onclick = function(event) {
// do something
}
// or in your case
button.onclick = addDie
3. Adding an event listener
With this approach, you can add any number of handler for your event in the button.
button.addEventListener("click", addDie);
button.addEventListener("click", dieRoll);
These three are the possible ways to handle the events using vanilla JS.
Since you are using jquery you can simply do,
$("#button2").click(addDie)
To make sure the events are attached safely you would need to wait till the document is loaded.
1. In Jquery
$( document ).ready(function() {
...
$("#button2").click(addDie)
...
}
2. In Vanilla JS
document.addEventListener("DOMContentLoaded", function(){
...
button.addEventListener("click", addDie);
button.addEventListener("click", dieRoll);
...
});
Knowing the above three ways will help you understand the ways events can be handled with vanilla js.
Based on the code you showed, I think the issue is that your script is in the head part, before the body (including the buttons) is even loaded.
That means that when you do $("#button0"), you get a collection of zero elements (the buttons don't exist yet), and then you attach a click handler to zero elements, so you are doing nothing.
The solution is simple: jQuery allows you in a very simple way to defer the execution of some code until the DOM has finished loading. That is done by calling $ as a function and passing a callback, i.e. $(...) (or, more verbosely, by writing $(document).ready(...)):
$(function () {
$("#button0").click(function(){
diceRoll = 0
for (i=diceAmt;i>0;i--) {
diceRoll += rand(1, diceSides)
}
document.getElementById("dieRoll").innerHTML = diceRoll;
})
})
That should fix the issue.

javascript, how to get html to persist after button click

Every time i click my HTML button the values are filled in for a brief flash and then disappear. want my variables to stay after the button is clicked. I I have tried putting the .innerHTML outside of the button click and altering just the variables in the js function. not sure what to do here. thanks.
HTML:
< button id="evaluteScoreButton">Evaluate Scores</button >
js:
document.getElementById("evaluteScoreButton").onclick = function evaluateGrades() {
window.document.getElementById('dsumm').innerHTML = arrayAverage(discussionArray());
window.document.getElementById('tsumm').innerHTML = arrayAverage(testArray());
window.document.getElementById('asumm').innerHTML = arrayAverage(assignmentArray());
var totalAverage = findTotalAverage();
window.document.getElementById('totalAverage').innerHTML = totalAverage;
window.document.getElementById('letterAverage').innerHTML = (findLetterGrade(totalAverage));
};
Change the button type
Instead of
<button id="evaluateScoreButton">Evaluate Scores</button>
Try
<input type="button" id="evaluateScoreButton">Evaluate Scores</input>
The reasoning behind this is that I think the <button> element is a Submit button which causes the html form to be posted. Using an <input> should avoid this

handling Javascript function

I have a JavaScript function which is used to copy data in my HTML page.
After clicking a button in the same HTML, a function is getting called. Till this everything is fine. But when I again click on same button, the same thing was getting copied twice. This should not happen. I want to copy content only one time.
<script language="JavaScript">
var x=1;
function h1b_cnslr() {
if (x===1){
x=2
some code
}
}
function h1b_nocnslr() {
if (x===1){
x=2
some code }
}
}
</script>
<BUTTON id ="btn_h1b_cnslr" class="copy" onClick="h1b_cnslr();" value="Copy" >Copy</BUTTON>
<BUTTON id ="btn_h1b_nocnslr" class="copy" onClick="h1b_nocnslr();" value="Copy" >Copy</BUTTON>
I am using variable x. The logic I used is, globally x=1 and when the user clicks for the first time x will get assigned 2. For the second click the value of x will be checked and if x===1, only then will it enter into the loop. But everytime x is assigned as 1 as I declared x as a global variable. Is their any other way to do this?
Put another var to check if you already have copied the content else skip copy

Javascript redirect when clicking on a div with a certain id

Here is an example of what I need help with: http://www.arbutusroofing.com/roofing-services/
When the user clicks on “READ MORE” (under each subject or category) and the light grey box pops up with more information, I want it to automatically redirect to another page in 10 seconds.
I know how to redirect to a different page when an actual link is clicked, but not with certain events like this.
Here is some example of the code:
<h6 id="displayText" style="margin-top: 0px; cursor: pointer;">
<u>READ MORE</u> ABOUT FLAT ROOFING
</h6>
I'm trying to redirect to a different page after 10 seconds when the id "displaytext" is clicked on.
Also, here is the code for the toggle text if you were wondering:
<script type="text/javascript">
$(document).ready(function() {
$("div#toggleText").hide();
$("h6#displayText").click(function(){
$(this).toggleClass("active");
$(this).next("div#toggleText").slideToggle();
});
});
</script>
You JS code:
function OpenNewTab(id){
setTimeout(function(){ window.location.href = "http://yourlinkhere/'+id+'"; }, 10000);
}
HTML:
<div onclick="OpenNewTab(1)">Readmore</div> // here 1 SHOULD BE UNIQUE ID AS PER RECORDS
You're probably looking for the javascript function setTimeout.
setTimeout(function(){ window.location.href = "http://somehwereblahblah"; }, 10000);
You can execute code with a delay using the setTimout function. An example of linking to google.com 10 seconds after the 'click' div is clicked:
<div onclick='setTimeout(function(){window.location = "http://www.google.com"}, 10000)'>Click</div>
I think you can use settimeout function. Eg:
setTimeout("location.href = 'http://insert-target-url';",1500);
setTimeout need two arguments. First is the action that will be executed. It can be simple redirect command, or event a function. The second one is the delay in milliseconds.
Hope this helps you.

How enable and disable setTimeout onclick

I have a function that executes on page load. The function executes every 30 seconds using setTimeout. I want to be able to enable and disable setTimeout onclick I have the following code below...
<input id="vw" value="" type="hidden">
<a href="#" onclick="document.getElementById('vw').value='0';>click here</a>
<script>
/* JAVASCRIPT BELOW */
function mPb(){
var vw = escape(document.getElementById('vw').value);
if(vw == ''){//DO NOT SWITCH VIEW IF EMPTY
var sTo = setTimeout("mPb()", 30000);
} else {
clearTimeout(sTo);
}
}//END VIEW MY FEED
//ON SERVICE LOAD DISPLAY SHITE INSTEAD OF ONLOAD
window.addEventListener ?
window.addEventListener("load",mPb,false) :
window.attachEvent && window.attachEvent("onload",mPb);
</script>
Your code works if you properly close your onclick attribute with a double quote:
click here
Also, here go two little suggestions to improve your code:
If you're checking for an empty string inside your function, why setting the input value to 0 when you click the link? It works, but it would be more clear if you set the value to ''.
When using setTimeout (and setInterval), do not pass a string containing a function call. It works too, but it's dangerous. Use this instead:
var sTo = setTimeout(mPb, 30000);
sTo needs to go outside of the mPb function, that way you can reference it from you onclick.

Categories

Resources