Remove javascript code using jQuery - javascript

I used
<div id="myJSDiv"><script>...</script></div>
$("#myJSDiv").html('');
and
<script id="myJSDiv">...</script>
$("#myJSDiv").remove();
but nothing removed.
JS script is
<script id="count_down">
var ss = 150;
function countdown() {
ss = ss-1;
if (ss<0) {
window.location="google.com";
}else {
document.getElementById("countdown").innerHTML=ss;
window.setTimeout("countdown()", 1000);
}
}
</script>

Once a script has loaded, removing the script tag it came from does not do anything to the functions or variables defined or created by that script.
There is no way to remove a block of code like that after it has loaded. Global functions can be redefined after they were loaded, but that's about all you can do. Perhaps, if you described the overall problem you are trying to solve, we could suggest a better approach.
Now that you've added the actual problem to your question, to stop your countdown timer, you can do this:
<script id="count_down">
var ss = 150;
var countdownTimer;
function countdown() {
ss = ss-1;
if (ss<0) {
window.location="google.com";
}else {
document.getElementById("countdown").innerHTML=ss;
countdownTimer = window.setTimeout(countdown, 1000);
}
}
function stopCountdown() {
clearTimeout(countdownTimer);
}
</script>
Just call the stopCountdown() function when you want to stop the countdown timer.

Related

Cant understand why my onclick does not work

I am currently studying Javascript and came across a problem while practising setInterval() and `clearInterval().
I am writing a timer that will stop as soon as I press on a button. I have a variable in which I start the interval, a function that executes the timer code and writes the current number the timer is on into a div in HTML.
Then I have a getElementById call that writes an onclick into a button with an id of theButton which contains a clearInterval.
The problem is, if I just write the clearInterval right in the end of the code, without an onclick, it works. But as soon as I write it inside an onclick, it doesn't work without even showing a error.
I have tried searching on the internet and the only answer I got was to use a var instead of a let for the variable with the interval, but that didn't work.
var timerVariable = setInterval(theTimer, 1000);
let count = 11;
function theTimer() {
if (count != 0) {
count--;
document.querySelector("div").innerHTML += count;
console.log("its working");
}
}
document.getElementById("theButton").onclick = 'clearInterval(timerVariable)';
The main reason it doesn't work is because you should assign a function reference to onclick, not a string. Your code should look something like this:
document.getElementById("theButton").onclick = function() {
clearInterval(timerVariable);
});
However, taking this a step further, the onclick is no longer considered good practice. A better solution is to attach your events using addEventListener(), like this:
document.querySelector('#theButton').addEventListener('click', () => {
clearInterval(timerVariable);
});
Here's a full working version with the above correction applied. Note that I added an else case to also clear the interval when the count reaches 0. Without this the interval will run infinitely without any purpose.
var timerVariable = setInterval(theTimer, 1000);
let count = 11;
function theTimer() {
if (count != 0) {
count--;
document.querySelector("div").innerHTML += count;
console.log("its working");
} else {
clearInterval(timerVariable);
}
}
document.querySelector("#theButton").addEventListener('click', () => {
clearInterval(timerVariable);
});
<button type="button" id="theButton">Stop</button>
<div></div>

Redirect with inactivity

My objective is to keep a user in a view as long as he/she keeps clicking a button within a certain lapse.
I'm using Rails and was exploring a solution via an embedded JS in the pertinent view.
So far I'm able to set a time after which the user will be redirected to root path with the following script:
var delayedRedirect = function (){
window.location = "/";
}
var delay = 10000;
$(document).ready(function() {
setTimeout('delayedRedirect()', delay);
});
I've been trying to write a function that resets the value of 'delay'or that calls the setTimeoutFunction again.
$('#btn-persist').click(function() {
delay = 3000;
// or calling again setTimeout('delayedRedirect()', delay);
});
But I noticed that changing the variable won't affect the setTimeout function that has already been called.
I've also tried to use the clearTimeout function as below without success
var delayedRedirect = function (){
window.location = "/persists";
}
var delay = 3000;
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
var stopRedirect = function (){
clearTimeout(triggerRedirect);
}
$(document).ready(function() {
triggerRedirect();
$('#btn-persist').click(function() {
stopRedirect();
});
});
I wonder why this may not be working and if there's any other way to stop the execution of the setTimeout function that has already been called so I can call it again to effectively reset the time to the original value of 'delay'.
At the same time, I don't want to stop any other JS functions that are running in parallel.
Do you see a better solution to achieve this?
The main problem why clearTimeout is not working. because you are clearing a anonymous function instead of a setTimeout variable
change this
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
to this
var triggerRedirect = setTimeout('delayedRedirect()', delay);
Edit:
also change this (if you want to restart the inactive redirect trigger)
$('#btn-persist').click(function() {
stopRedirect();
});
to this
$('#btn-persist').click(function() {
stopRedirect();
triggerRedirect();
});

jQuery, update content when necessary

I'm trying to update contents of a chat located in div (div1) but only when the contents of div1 change (a message was submitted into db and picked up in div1).
I tried the solution from here but my get fails to compare the data.
This solution works perfectly but without content comparison:
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",2000);
}
function startTime()
{
jQuery('#div1').load('index.php #div1 > *');
}
This is the modification based on this, which fails:
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",2000);
}
function startTime()
{
var $main = $('#div1');
$.get('chat.php #div1', function (data)
{
if ($main.html() !== data) $main.html(data);
});
}
I tried various modifications of this code but to no avail...
I can't reload the entire page and I don't want to do this if not necessary since it makes the chat harder to read if you have to scroll trough the messages.
How can this be fixed?
UPDATE
Based on #T.J's suggestions I modified the code which now works perfectly:
window.onload = startInterval;
function startInterval()
{
setInterval(startTime,3000);
scrolDown();
}
function startTime()
{
var $main = $('#div1');
$.get('#div1', function (data)
{
elements = $(data);
thisHTML = elements.find("#div1").html();
if ($main.html() !== thisHTML) {
$main.html(thisHTML);
scrolDown();
}
});
}
The other problem was that get required library:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
which apparently was not required by the load which I used previously.
You want to use get, but you want the fragment feature of load, so you'll have to do that work yourself. Then remember what you got last time, and only update if it's not the same:
var lastHTML;
function startTime()
{
var $main = $('#div1');
$.get('chat.php', function (data) // <== Or index.php, the question has both
{
var elements, html;
// Turn the HTML into elements
elements = $(data);
// Get the HTML of *only* the contents of #div1
html = elements.find("#div1").html();
// If that has changed, use it
if (lastHTML !== thisHTML) {
lastHTML = thisHTML;
$main.html(thisHTML);
}
});
}
Note that that's a fairly basic implementation of the fragment feature (it doesn't, for instance, strip out scripts the way load does). You may want to look at how load does its fragment stuff and replicate that (the joy of open source).

My Javascript timer counting down too fast or it doesn't start onLoad

I have that Javascript counter:
var x=100;
function timerCountdown()
{
document.getElementById('timer1').value=x;
x--;
t=setTimeout("timerCountdown()",1000);
if (x<-1)
{
document.getElementById('timer1').value='Done!';
clearTimeout(t);
}
}
function stopCounter(){
clearTimeout(t);
x=x+1;
}
Then I use:
<body onFocus='timerCountdown()' onBlur='stopCounter()'>
But the problem is, the countdown doesn't start when the page loads. It waits for me to click on another window and to reFocus on the window again.
So I tried this:
<body onLoad='timerCountdown()' onFocus='timerCountdown()' onBlur='stopCounter()'>
But this time, the countdown goes pretty fast. Probably because timerCOuntdown is called twice every second.
Alternatively, I could just use the onFocus and onBlur in the body tag, but I need a function to trigger the Focus upon body load. Is that possible?
Does anyone have a suggestion to solve this problem?
thanks a lot!
The simple answer is because setTimeout is invoked twice, running timerCountdown() once for two times separately, and continually setting two setTimeout IDs.
This would be what you want:
var x = 100;
var t = 0;
function timerCountdown()
{
if (t == 0) t = setInterval(timerCountdown, 1000);
document.getElementById('timer1').value=x;
x--;
if (x < 0)
{
document.getElementById('timer1').value='Done!';
clearTimeout(t);
ticker = 0;
}
}
function stopCounter()
{
clearTimeout(t);
t = 0;
x++;
}
setInterval is much more suited for countdown timers, and things you need to run continually since setTimeout only runs once and you need to keep on calling it.
Edit: This fixes the initial rapid triggering of the timer on Firefox.
Remove the handler from <body onload= and add this to the end of the script block above:
t = setInterval(timerCountdown, 1000);

Javascript Timing

I am trying to create a countdown using javascript. I got some code from here and modified it slighly.
<script type="text/javascript">
var c=10, t;
function timedCount() {
document.getElementById('txt').value=c;
c=c-1;
t=setInterval("timedCount()",1000);
}
function stopCount() {
clearInterval(t);
}
</script>
I need to call a countdown repeatedly until the user clicks on a link. It should countdown from 10 by 1 every second (10,9,8,7,6...0) until the link is clicked but it doesn't. Can anybody help me?
EDIT:
Does anyone know how to make the countdown restart once it hits 0?
Thank you in advance.
<script type="text/javascript">
var c=10;
var t;
function timedCount()
{
document.getElementById('txt').value=c;
c=c-1;
}
function startCount()
{
if (!t) t=setInterval("timedCount()",1000);
}
function stopCount()
{
clearInterval(t);
t=null;
}
</script>
Call startCount() in onload (or whatever) when you want the counter started. Note my startCount and stopCount don't create multiple interval timers.
Also, the element with id=txt needs to be an <input> or <textarea> box for your code to work. If it's a span, you should use document.getElementById('txt').innerHTML=c;
Finally, you might want timedCount() to stopCount() if c goes below zero. This is easy enough:
if (c <= 0) stopCount();

Categories

Resources