innerHTML.indexOf when reloading div not working - javascript

I have the following script. It works fine if I reload the page but I would prefer to make it work with just reloading the div but it seems that innerHTML.indexOf doesn't pick up on changes in a div without reloading the whole page which looks a bit ugly. How can I check for the string in the logs div without using location.reload()?
<div id="logs"><?php echo nl2br( file_get_contents('/path/myfile') ); ?></div>
<script>
var myVar = setInterval(myTimer, 2000);
function myTimer() {
$("#logs").load(window.location.href + " #logs" );
location.reload();
}
if (document.getElementById("logs").innerHTML.indexOf("thisistheend") != -1) {
clearInterval(myVar);
}
</script>
edit: I also tried putting the conditional inside the myTimer function but that did not work.

You should declare if statement inside of myTimer. Otherwise, the if statement will only be executed once on the first render.
var myVar = setInterval(myTimer, 2000);
function myTimer() {
$("#logs").load(window.location.href + " #logs" );
if (document.getElementById("logs").innerHTML.indexOf("thisistheend") != -1) {
clearInterval(myVar);
}
}

Related

How can I open two URLs with a five second delay?

I have the below javascript code. Basically what I want to do is when a user is clicking on the hyperlink, I want to open a new tab, call https://somesite.com/logout, first, wait 5 seconds and then call https://www.somesite.com
This is possible to do? If so, what changes can I make to this code to get that done?
script type="text/javascript">
window.onload = function() {
document.getElementById("mySite").onclick = function() {myFunction()};
function myFunction() {
//your code goes here
var win1= window.open("https://somesite.com/logout");
win1.close();
}
};
</script>
<a href='https://www.somesite.com' target='_blank' id='mysite'>Click Here</a>
window.onload = function() {
document.getElementById("mysite").onclick = function() {myFunction()};
function myFunction() {
//your code goes here
var win1= window.open("https://somesite.com/logout");
win1.close();
window.setTimeout(function() {
window.open("https://somesite.com");
}, 5000);
}
};
getElementById is case sensitive, so be sure to use "mysite". You can set a timeout to open a window after 5000ms (5 seconds).
Also, be aware that browsers will typically block popups by default.
Just add window.setTimeout(window.location.reload(), 5000) after close()

Having difficulty finishing this time-based code snippet

var myVar = setInterval(myTimer, 1000);
var button = document.querySelector(".button");
function myVarFunction() {
setInterval(myTimer, 1000);
}
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function clockButton(document.querySelector(".button").toggle(".clockOn")){
if(button.hasAttribute("class","clockOn")){
clearInterval(myVar);
}else{
myVarFunction();
}
}
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="clockButton()" class = "button clockOn" >button</button>
</body>
</html>
I'm trying to execute a code snippet that will display the time in real-time (using the setInterval() method) and a button that when clicked will stop the time running in real-time, but if clicked again the time will run in real-time as it did before(using .toggle() to achieve this).
here is a link to the w3schools exercise where I got this idea from:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_setinterval_clearinterval
For some reason the time completely dissapears, none of my code works and I can't work out why
Skip to the end if you just want the answer
First thing's first, remove your onClick event from the HTML and place it in your script. This is the recommended way to set up events.
<button class="button clockOn">button</button>
and
var myVar = setInterval(myTimer, 1000);
var button = document.querySelector(".button");
// Add the event listener here
button.addEventListener("click", clockButton);
Now there's a couple of issues, but your most prominent one is the clockButton function. What you've got here is invalid JavaScript, you cannot execute code within the parameter list of a function:
function clockButton(document.querySelector(".button").toggle(".clockOn")){
...
}
You need to move this code to the body of the function instead.
function clockButton () {
document.querySelector(".button").toggle(".clockOn");
...
}
That fixes the first problem, which is just invalid code. But the next problem you're going to face is that toggle(...) is not a function of the button element, (You may be confusing a bit of jQuery here, which has happened to me a number of times). You don't actually need this line of code though anyway, so you can remove it, and write your own class toggle.
It's fairly straightforward to write a class toggle, and you're actually doing a check already for the buttons class in your if statement, so it's a naturally obvious place for you to write the class toggle:
if(button.hasAttribute("class","clockOn")){
...
}
But unfortunately, there's a problem with the code above. Calling the hasAttribute function on an element will just check whether that attribute exists, not if it actually has a certain value. So in your case it will always be true, as you're never removing the class attribute, only changing it to something different.
To fix this up, you can use the classList functionality, which is the standard these days to deal with element classes in the native DOM API. You want to check that the element has the class clockOn so you can change the if statement to this:
if (button.classList.contains("clockOn")) {
...
}
To remove the class, you can use the remove function on the classlist like so:
button.classList.remove("clockOn");
And you can add the class back using
button.classList.add("clockOn");
So all in all, your function becomes this
function clockButton(){
if(button.classList.has("clockOn"){
clearInterval(myVar);
button.classList.remove("clockOn");
}
else {
myVarFunction();
button.classList.add("clockOn");
}
}
Now that you're here, your button should work to stop the clock, and restart it again when you click it a second time, but it's not working properly yet, because you'll notice if you click it again, the time does not stop.
This is because myVarFunction does not reassign the new interval handle to the myVar variable. Every time you call setInterval you should get a new handle. So as an example, imagine that the first time you call setInterval it assigns the handle of 123.
var myVar = setInterval(myTimer, 1000);
// myVar === 123
Now clearInterval(myVar) will clear the running interval.
The next time you set the interval, it is within myVarFunction, lets say for example, it returns 456 the next time it's called.
function myVarFunction() {
// setInterval returns `456`
setInterval(myTimer, 1000);
// myVar is still equal to `123`
}
The next time you try to clear the interval, you are clearing 123 (since you never reassigned the myVar variable) which doesn't exist, you should be clearing 456 which was the new interval you just set up.
So it's an easy fix
function myVarFunction() {
myVar = setInterval(myTimer, 1000);
}
TL;DR
Your code should look something like this
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<!-- Remove the onclick event from here -->
<button class="button clockOn" >button</button>
</body>
</html>
var myVar = setInterval(myTimer, 1000);
var button = document.querySelector(".button");
button.addEventListener('click', clockButton);
function myVarFunction() {
myVar = setInterval(myTimer, 1000);
}
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function clockButton(){
if(button.classList.contains("clockOn")){
clearInterval(myVar);
button.classList.remove("clockOn");
}
else {
myVarFunction();
button.classList.add("clockOn");
}
}
See it live
JSFiddle
You can check my implementation below, the time continues from the current realtimee after toggling, I guess this is what you want.
let time = document.getElementById("demo")
let myIntervalTimer;
function myStartFunction() {
if(myIntervalTimer){
clearInterval(myIntervalTimer)
}
myIntervalTimer = setInterval(myTimer, 1000)
}
function myStopFunction() {
clearInterval(myIntervalTimer)
}
function myTimer() {
let d = new Date();
let t = d.toLocaleTimeString();
time.innerHTML = t;
}
let timeClassList = time.classList
function toggleTime() {
if(timeClassList.contains('showTime')) {
myStopFunction()
}
else {
myStartFunction()
}
timeClassList.toggle("showTime")
}
myStartFunction()
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo" class='showTime'></p>
<button onclick="toggleTime()">Toggle time</button>
</body>
</html>

Button to refresh page every second/minute etc?

I'm wanting a button that when clicked will refresh the current page after a specified amount of time.
I currently have:
<script type="text/javascript">
setTimeout(function reload(){
location = ''
},1000)
</script>
<button onclick="reload()">Reload</button>
However, that JUST reloads the page without even having to click the button. I'm wanting the button to execute the script, and also a button to STOP the page reload.
This should be really simple but I can't figure it out :(
******EDIT**********
I'd also like the script to run on an infinite loop after the button is clicked.
Your setTimeout is called on page load. You need to put it inside the reload() function:
function reload() {
setTimeout(function() {
window.location.reload();
}, 1000);
}
To make the timer run every x seconds and reload only a part of the page you would need to use setInterval and an AJAX request, something like this:
var timer;
function reload() {
timer = setInterval(function() {
$.post('foo.html', function(data) {
$('#bar').html(data);
});
}, 1000);
}
function clear() {
clearInterval(timer);
}
This should do the trick
<script type="text/javascript">
function reload(){
setTimeout(function(){location.reload()}, 3000);
}
</script>
<button onclick="reload()">Reload</button>
What you wrote is
window.setTimeout("location = ''"; ,1000);
You were saying execute this function after 1 second. You need to define the setTimeout inside the function. Also there is a built in method to reload the page. Call that instead of setting the location to a blank string.
function reload() {
setTimeout( function() {
window.location.reload(true);
},1000);
}
Now to cancel the timeout, you need to use clearTimeout(timeoutId); You get the timeoutId from the integer that the setTimeout returns when you call it.
var timer = null;
function reload() {
timer = window.setTimeout( function() {
window.location.reload(true);
},1000);
}
function cancelReload() {
if (timer) {
window.clearTimeout(timer);
}
timer = null;
}
AND you said you want it to keep running. That will require cookies or localstorage.
var timer = null;
function reload() {
localStorage.reload = true; //set localstorage so we know to fire it off again
timer = window.setTimeout( function() {
window.location.reload(true);
},1000);
}
function cancelReload() {
if (timer) {
window.clearTimeout(timer);
}
timer = null;
localStorage.removeItem("reload"); //remove the key in localstorage
}
if (localstorage.reload) { //check localstorage to see if key is set
reload();
}
You need to wrap the whole thing in another function and call that from the button click

Autosave using javascript issue

The following piece of code autosaves a page but it also times it out by loging out and taking the user to a time out page. How can i chnage it so that it only does the auto save part but not the time out?
<script language='javascript'>
function Save() {
var hdnSessionTimeOut = document.getElementById('fast22_MainCtn_fast44');
hdnSessionTimeOut.value = 'SessionTimeOut';
__doPostBack('Fast22$MainCtn$btnSave', '');
}
function Redirect() {
window.location = "SessionTimeout.aspx"
}
window.onload = function () {
if ('True' == 'True') setTimeout(Save, 30000);
else setTimeout(Redirect, 30000);
}
</script>
I tried reducing it to the following but and I think it worked but it changed the doc to view mode instead of edit mode. and you have to click edit again. Also when it in edit mode, the counter still works and it gives and error. Is there a way to have it auto save and then go back again to edit mode?
<script language='javascript'>
function Save() {
__doPostBack('ctl00$MainContentPlaceHolder$btnSave', '');
}
window.onload = function () {
if ('True' == 'True') setTimeout(Save, 10000);
else setTimeout(Save, 25000);
}
</script>

scroll to bottom of the div doesn't work

function ereja(){
var newscrollHeight2 = $("#messages")[0].scrollHeight;
return newscrollHeight2;
}
var newscrollHeight = ereja();
var oldscrollHeight = $("#messages")[0].scrollHeight;
function merrmesazhet(){
$('#messages').load(
"nxirr_mesazhet.php?room=<?php echo urlencode($dhoma24); ?>"
);
setTimeout(ereja, 1000);
if( newscrollHeight != oldscrollHeight ){
$("#messages").scrollTop($("#messages")[0].scrollHeight);
}
}
What's wrong with this code? Why it doesn't work? I am trying to scroll to bottom of the div when a user writtes a new message. Any idea?
Assuming you are actually calling merrmesazhet() and that you are testing on IE>=8 as lower versions don't support scrollHeight. Then your main issue is the use of setTimeout which is essentially calling ereja every second and doing nothing.
Indeed you do not even need the JS timer - you are using jQuery which supports a callback in it's load function (which executes once on a successful load rather than repeatedly). Your if-statement in it's current form will always evaluate to false as it isn't within the function executed on the timer anyway.
Something like this may work for you:
var oldscrollHeight = $("#messages")[0].scrollHeight;
function merrmesazhet(){
$('#messages').load(
'nxirr_mesazhet.php?room=<?php echo urlencode($dhoma24); ?>',
function(){
var newscrollHeight = $("#messages")[0].scrollHeight;
if( newscrollHeight != oldscrollHeight ){
$("#messages").scrollTop($("#messages")[0].scrollHeight);
}
}
);
}
jsFiddle

Categories