I'm looking for some solution to manipulate a part of HTML body scrip function by injecting some code using tampermonkey on every site load. The purpose of this workaround is to manipulate function behavior. Here's a simple example of what it's going to do:
<html>
<body>...</body>
<script type="text/javascript">...</script>
<script type="text/javascript">
function dosome() {
...
};
function startTimer() {
var countDownTime = 1000 * 60;
...
};
</script>
</html>
For instance in code above, line var countDownTime = 1000 * 60; changes to var countDownTime = 1000 * 45;
You could attempt it by having the parameter be inputted through an input field. See code example below:
<html>
<body>
<input type="number" id="testInput" name="testInput" value="0">
<button type="button" onclick="startTimer()">Submit</button>
<p id="output">Output: </p>
</body>
<script type="text/javascript">
function startTimer() {
var countDownTime = 1000 * document.getElementById("testInput").value;
document.getElementById("output").innerHTML = 'Output: ' + countDownTime;
};
</script>
</html>
You could also make the call from within a button by using the OnClick event.
Related
My script is working well, but the only problem i have.
i want to show the counter in human readable style, becouse now its showing in milliseconds
i want like time left is 1:02 Minutes
so i want to display time left in readable style in browser not milliseconds
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<body>
<p>Time left: <span id="timr"></span></p>
<p id="hpd">Welcome here john</p>
<p id="shp" style="display:none">Your time is up</p>
<input type="button" value="Hi john" id="btn">
<script>
var SessionTime=100000;
var tickDuration=1000;
var myInterval=setInterval(function(){
SessionTime=SessionTime-tickDuration
$("#timr").text(SessionTime);
},1000);
var myTimeOut=setTimeout(SessionExpireEvent,SessionTime);
$("input").click(function(){
clearTimeout(myTimeOut);
SessionTime=100000;
myTimeOut=setTimeout(SessionExpireEvent,SessionTime);
});
function SessionExpireEvent()
{ clearInterval(myInterval);
$("#btn").attr("disabled", true);
$("#hpd").hide();
$("#shp").show();
}
</script>
</body>
</html>
You can simply replace
$("#timr").text(SessionTime);
with
$("#timr").text(`${Math.floor(SessionTime/60000)}:${SessionTime/1000%60}`);
However, your code can be simpler if you don't need to know how much time is left to milliseconds precision.
setInterval and setTimeout are the only functions in your code that need their arguments in milliseconds.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<body>
<p>Time left: <span id="timr"></span></p>
<p id="hpd">Welcome here john</p>
<p id="shp" style="display:none">Your time is up</p>
<input type="button" value="Hi john" id="btn">
<script>
var SessionTimeInSec = 40;
var myInterval = setInterval(function() {
SessionTimeInSec--;
$("#timr").text(`${Math.floor(SessionTimeInSec/60)}:${SessionTimeInSec%60}`);
}, 1000);
var myTimeOut = setTimeout(SessionExpireEvent, SessionTimeInSec*1000);
$("input").click(function() {
clearTimeout(myTimeOut);
SessionTimeInSec = 40;
myTimeOut = setTimeout(SessionExpireEvent, SessionTimeInSec*1000);
});
function SessionExpireEvent() {
clearInterval(myInterval);
$("#btn").attr("disabled", true);
$("#hpd").hide();
$("#shp").show();
}
</script>
</body>
</html>
I did the following changes:
Change SessionTime to SessionTimeInSec and divide numbers by 1000.
Multiple SessionTimeInSec by 1000 for the arguments passed to both funtions setInterval and setTimeout.
Get rid of tickDuration since it will equal to one. Consonantly, change SessionTime = SessionTime - tickDuration to SessionTimeInSec--.
Change $(#timr) text to 0:0 in SessionExpireEvent()
Seems like you want something like this:
var mins = Math.floor(SessionTime / 1000 / 60);
SessionTime %= 60000;
var secs = SessionTime / 1000;
$("#timr").text(mins + ":" + secs);
AddEventListener won't work when I clicked the button, the class name is exact on the html.
And how to properly set the time interval. I want the ball rolling and stop on the given time example 10s.
This is the html file and below is the js code
<!DOCTYPE html>
<html>
<link rel ='stylesheet' href ="style.css">
<script src = 'main.js'></script>
<body>
<div class = "wrapper_main" align ='center'>
<div > This is a lotto app design sample
<div class="ball-size">
<img src = "numbers/ball-0.png" class = "balls-0">
<img src = "numbers/ball-0.png" class = "balls-1">
<img src = "numbers/ball-0.png" class = "balls-2">
</div>
<div onclick="myFunction()" class ="buttons">
<button class = "btn-roll"> Roll </button>
</div>
</div>
</div>
</body>
</html>
js file ----
document.querySelector(".btn-roll").addEventListener("click", myFunction);
/*
var timesRun = 0;
var interval = setInterval(myFunction, 0);
timesRun += 1;
if(timesRun ===10) {
clearInterval(interval);
} */
function myFunction() {
var balls, balls1, balls2;
balls = Math.floor(Math.random() * 10);
balls1 = Math.floor(Math.random() * 10);
balls2 = Math.floor(Math.random() * 10);
var ballsDOM = document.querySelector(".balls-0");
var ballsDOM1 = document.querySelector(".balls-1");
var ballsDOM2 = document.querySelector(".balls-2");
ballsDOM.src = "numbers/ball-" + balls + ".png";
ballsDOM1.src = "numbers/ball-" + balls + ".png";
ballsDOM2.src = "numbers/ball-" + balls + ".png";
console.log("done");
}
It is important to do the event biding, after the DOM is created and the button exists in the page.
For example this won't work:
<body>
<script>
document.querySelector('.btn-roll').addEventListener('click', myFunction);
function myFunction(){
alert(1);
}
</script>
<button class="btn-roll">click on me</button>
</body>
Because we binded an event on a button that is not exists yet. but:
<body>
<button class="btn-roll">click on me</button>
<script>
document.querySelector('.btn-roll').addEventListener('click', myFunction);
function myFunction(){
alert(1);
}
</script>
</body>
Will work fine.
You can use libraries like jQuery to ensure the DOM is ready like this:
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
document.querySelector('.btn-roll').addEventListener('click', myFunction);
// or:
// $('.btn-roll').on('click',myFunction);
})
function myFunction(){
alert(1);
}
</script>
<button class="btn-roll">click on me</button>
</body>
Hi this is my first javascript and it is not working. The script is programmed to display a clock. The code is as follows:
<html>
<head>
<script type="text/javascript" src="clock.js" > </script>
</head>
<body onload=display_ct();>
<span id='ct' ></span>
</body>
</html>
The javascript is :
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
When execute I get a blank screen. What and where is the mistake ?
TIA :)
You should probably be consistent with ending lines in semi-colon. Also, you should check that clock.js is loading; finally put the onload handler in quotes like
function display_c() {
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout('display_ct()', refresh);
}
function display_ct() {
var x = new Date();
document.getElementById('ct').innerHTML = x;
tt = display_c();
}
<html>
<body onload="display_ct();">
<span id='ct'></span>
</body>
</html>
Please enclose your onload attribute value of body tag inside " " .
It should be
<body onload="display_ct();">
Try using setInterval(), also this line won't work in some browsers:
setTimeout('display_ct()',refresh)
var ct;
function display_c() {
//timer block
setInterval(function() {
ct.innerHTML = new Date().toString();
}, 1000); //execute every 1 second
}
function display_ct() {
ct = document.getElementById('ct'); //initialize once.
display_c();
}
<!-- onload, enclosed in quotes -->
<body onload="display_ct()">
<span id='ct'>Loading ...</span>
</body>
You made two errors when entering the display_ct function. You needed to wrap the <body>'s onload event with quotes, and remove the quotes and the parentheses on the setTimeout. See below.
function display_c() {
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout(display_ct, refresh);
}
function display_ct() {
var x = new Date();
document.getElementById('ct').innerHTML = x;
display_c();
}
<html>
<head>
<script type="text/javascript" src="clock.js">
</script>
</head>
<body onload="display_ct()">
<span id='ct'></span>
</body>
</html>
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 9 years ago.
<html>
<head>
</head>
<body>
<script>
function toD(angle) {
return angle * (180 / Math.PI);
}
var a = document.getElementById('test').innerHTML = toD(15);
</script>
<p id='test'> </p>
</body>
</html>
Sorry, i'm not sure if i'm missing something, but how come this code isn't running? thank you in advance, sorry if this is a stupid question!
At the time of running var a = document.getElementById('test').innerHTML = toD(15); in your script <p id='test'> </p> does not exist.
place the script AFTER <p id='test'> </p> or wrap the entire script in its own function and assign it to onload so that it is only ran after <p id='test'> </p> and the rest of the DOM is available.
Either
<html>
<head>
</head>
<body>
<p id='test'> </p>
<script>
function toD(angle) {
return angle * (180 / Math.PI);
}
var a = document.getElementById('test').innerHTML = toD(15);
</script>
</body>
</html>
OR
<html>
<head>
</head>
<body>
<script>
window.onload = function() {
function toD(angle) {
return angle * (180 / Math.PI);
}
var a = document.getElementById('test').innerHTML = toD(15);
}
</script>
<p id='test'> </p>
</body>
</html>
Note: this is a very dirty way of using window.onload, that should only be used if this is to be the only script on the page that requires onload. For more information about using onload properly when there will be multiple scripts using it, please read How to Use window.onload the Right Way
You need to wait until the document loads, as you're trying to access an element (#test) before the HTML has been fully parsed by the browser - you can use window.onload so that your JS is run after the document has been loaded - e.g.
window.onload =
// JS
Look at the JavaScript console [f12] and you will see an error message:
Uncaught TypeError: Cannot set property 'innerHTML' of null
The error occurs because you are referencing the element before it is rendered to the page.
Put the script tag after the element so it can find the element.
<html>
<head>
</head>
<body>
<p id='test'> </p>
<script>
function toD(angle) {
return angle * (180 / Math.PI);
}
var a = document.getElementById('test').innerHTML = toD(15);
</script>
</body>
</html>
Because when you run document.getElementById('test') the DOM object <p id='test'> </p> wasn't rendered yet.
Problem in rendering
Change your code as below :
<html>
<body>
<p id='test'> </p>
<script language="javascript">
function toD(angle) {
return angle * (180 / Math.PI);
}
var a = document.getElementById('test').innerHTML = toD(15);
</script>
</body>
</html>
-> Please read about how web page is parse. you will clear your idea about where to write script in your page.
->object should be rendered before performing operation on it. in your code div is not rendered and you try to perform operation on it ( i.e. document.getElementById('test').innerHTML = toD(15); )
Place the script at the bottom of the page to avoid problems like this noted above, also use windows.onload http://www.w3schools.com/jsref/event_onload.asp - to ensure the element is rendered before you cast on it.
I want to do display time-changing data on a web page. I use the JQuery framework. I use the following code as a test : display a different random number each second. It does not work. Why ? What is a correct, working way ?
<html>
<head>
<title>test</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function refreshRandomNumber() {
var lHtmlBlob = "<p> random = " + Math.random() + "</p>";
$('#random_number').html(lHtmlBlob);
}
setInterval(refreshRandomNumber(), 1000);
});
</script>
</head>
<body>
<div id="random_number"></div>
</body>
</html>
You need to pass setInterval just the function referenced by refreshRandomNumber and not the return value of that function what you do by using refreshRandomNumber(). So try this:
setInterval(refreshRandomNumber, 1000);
Small difference. instead of:
setInterval(refreshRandomNumber(), 1000);
use:
setInterval(refreshRandomNumber, 1000);
That passes the function rather than the function return value.