So I have a variable that is constantly changing (num) and it's controlled by other page, but to get the value from other page to another, I need to refresh the page. I tried auto refresh, but I have a youtube video playing and it would stop every refresh. Is there any way to refresh the variables only? Or constantly doing the javascript of the file so the values are always being updated.
EDIT: I am not using any server side or server language. Just HTML and JS
I believe the function you are looking for is setInterval(). This function will call a child function every time a certain period of time passes. In a limited use case, you can register a variable in a script and also register an interval timer to update it periodically. Depending on your use case, you may need to also write some JS to bind the new value of the number to the DOM.
Here is an example of using the intervals. In this example, clicking the button once begins the timer. After that, the interval (1000ms) will fire an event automatically to update the x variable and bind the new value to the DOM.
<!DOCTYPE html>
<html>
<body>
<button id="eventBtn" onclick="myFunction()">X = 0</button>
<script>
var x = 0;
function myFunction() {
setInterval(function(){
x++;
var btn = document.getElementById("eventBtn");
btn.innerHTML = 'X = ' + x;
}, 1000);
}
</script>
</body>
</html>
Interactive JS Fiddle for example
W3Schools - "Window setInterval() Method"
Related
Looking for a way to track if an element has been clicked multiple times (for example, a user clicks "Submit" button several times to place an order).
We are doing some work redeveloping a website and in our UX research we found that people don't download PDFs from the site because the link behind the button is broken. We noticed that people tend to click the button several times before giving up, yet some still manage to download the PDF.
In order to show our changes to code have improved site performance and user experiences, we want to show that these "multiple clicks" have decreased.
Since the site uses Google Analytics, I have tried to create a variable in GTM that counts clicks on the same click element (which doesn't work):
function() {
var the_div = {{Click Element}};
var clickCount = 0;
return clickCount;
}
I expect the output to be a count of the times I've clicked on the Click Element (1, 2, 3, etc....)
Try like this.
Define a varable for count. and on each click increment it.
var i = 1;
$('#elem').on('click',function(){
console.log(i);
i++;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="elem">click here</div>
sorry for the delay in responding.
We found a solution.
As Piertstorff pointed out, the variable sets clickCount to zero every time it is called. The solution, was to build a custom HTML tag (that runs JS) - not a variable - that fires on a Page Load Trigger and listens for multiple clicks within a 2-second timeframe. The HTML tag then passes an event to the DataLayer and stored in a variable.
That variable (signalling multiple clicks occurred) activates a trigger for another tag that passes the {{Click Classes}} variable to GA
Use javascript variable with global scope
<script>
countClicks = 0;
function clickCountFunction() {
countClicks++;
}
</script>
Add onClick attribute in button and call clickCountFunction() in it
I have a simple javascript program that runs onclick of an image.
However, whenever I clicked the image, the page reloaded.
After a lot of debugging I found that the page doesn't reload until right as the script completes.
There are several setTimeouts in the code, but I noticed the page was reloading instantly. I even changed these timeouts to 15000 milliseconds, but it still reloads immediately.
I am using jquery, if it makes any difference.
I also want a different result from the program every time you click it, so that each time you click it a different script runs and a some text changes in a specific order. I did this by changing the onclick attribute of the images in each script to the name of the next script, so that script one would switch onclick to script two, and so on. I set a timeout on these switches so that one click doesn't race through every single script. script two isn't running, so that much works.
my code:
function getSounds() {
console.log("script. initiated");
$("#soundwebGetSoundDirections").html("Now, Wait until the file is done downloading and click below again.");
console.log("new message");
$("#soundwebGetSoundA").attr('href',"");
console.log("href eliminated");
setTimeout($("#soundwebGetSoundImg").attr('onclick','findFile()'),2000);
console.log("onclick to findFile()");
}
function findFile(){
console.log("FINDFILE")
$("#soundwebGetSoundDirections").html("Find the file(it's probably in your downloads), copy the path of the file (usually at the top of the file explorer) and paste in it the box below. Then, make sure there is a '/' at the end of the path and type 'Linkiness.txt' (case sensitive, without quotes) at the end. Once you have all that stuff typed, click the icon again.");
console.log("FIND IT, DARN IT!!");
$("#soundwebGetSoundPathInput").css("opacity",1);
console.log("diving into reader");
setTimeout($("#soundwebGetSoundImg").attr('onclick','readFile()'),1000);
}
function readFile(){
console.log("loading...");
$("#soundwebGetSoundDirections").html("loading...");
if(document.getElementById("soundwebGetSoundPathInput").value.length == 0){
setTimeout($("#soundwebGetSoundDirections").html("Please fill in Path!"),1000);
setTimeout(findFile(),2000);
}
}
and the HTML that's linked to,
<a id = "soundwebGetSoundA" href = "https://docs.google.com/feeds/download/documents/export/Export?id=1ynhHZihlL241FNZEar6ibzEdhHcWJ1qXKaxMUKM-DpE&exportFormat=txt">
<img onclick = "getSounds();" class = "soundwebImgResize" src = "https://cdn3.iconfinder.com/data/icons/glypho-music-and-sound/64/music-note-sound-circle-512.png" id = "soundwebGetSoundImg"/>
</a>
Thanks for any help,
Lucas N.
If you don't want clicking the image to cause the anchor tag to load the href, then move the image tag outside of the anchor tag.
You aren't using setTimeout correctly. You should be passing in a function not a statement. So, for example, instead of
setTimeout($("#soundwebGetSoundDirections").html("Please fill in Path!"),1000);
setTimeout(findFile(),2000);
you should use
setTimeout(function () { $("#soundwebGetSoundDirections").html("Please fill in Path!") },1000);
setTimeout(findFile,2000);
I think the same goes for setting the onclick attribute but I've never tried dynamically changing an onclick attribute like that.
Since you're already using jQuery you could try using .on('click'... and .off('click'... if your current setup isn't working.
Hopefully a simple question; if I create a timer using JavaScript embedded within my page, and I then navigate away from that page, will the timer be automatically cancelled or will it continue to run?
EDIT
Expanding the question, if that page were to perform a post-back (in my case, this is ASP.NET Forms), and the script is rendered as a part of the page markup, would the original timer created when the form is first displayed be cancelled during that post-back or would a second timer be created?
Example (rough typed):
<body>
...
<script type='text/javascript'>
function doSomething() { ... }
x = setInterval(doSomething(), 60000);
</script>
...
<button type="submit" />
...
</body>
Following the post-back, a new timer will be created as a result of the page being re-rendered, how many timers are now running (assuming the post-back was within the interval specified by the timer)?
It'll be automatically cancelled. JavaScript code is executed within the context of a page.
Think about a page like an application. Switching to other page is like closing an application and opening a new one. This also applies to a full page refresh (i.e. when you press F5).
I have a regular time interval event in javascript which clicks an asp button. The application is a common chat room and I have to refresh the gridview (which is inside a panel) to check for new chats. But everytime the button is clicked and gridview is refreshed the panel scrolls up to the top (i.e., scrollTop value becomes 0). I have tried this but to no avail:-
<script type="text/javascript">
function refresh() {
setInterval(function () {
var xtop = document.getElementById("Panel1").scrollTop;
document.getElementById("Button2").click();
document.getElementById("Panel1").scrollTop = xtop;
}, 1000);
}
</script>
If you want to store the scroll position between postbacks, in your refresh() function you can store the scroll position value in a hidden field that you put somewhere in your HTML: <input type="hidden" id="scroll"></input> using JavaScript
document.getElementById("scroll").value = document.getElementById("Panel1").scrollTop;
There are other options to persist data such as cookies and the ASP.NET ViewState, but a hidden field is simplest for this purpose. You can then read this value from the hidden field upon loading the DOM and scroll the window to that position.
However, if you are posting back every second to check for new messages, you probably have a bigger problem. This kind of functionality is better done asynchronously with AJAX. It will need a bit of looking into as I'm not sure of your implementation here, but essentially you will use JavaScript to ask the server if there are new messages and load them from the server asynchronously, thereby eliminating the use of postbacks.
Here is Mozilla's introduction to AJAX.
Hey guys I have a javascript function that keeps persisting even when navigating to another page (single page templates not multipage) in Jquery Mobile
<script type="text/javascript">
setInterval("window.location.reload();", 5000);
</script>
How do I ensure that this only occurs on the page from which it is called rather than it calling it on every page I link to with ajax based navigation?
I am using Jquery Mobile 1.2
Bind it to the page where you want it to occur. Replace $('.selector') with pageID, e.g. $('#home'). You could also be more specific $('div[data-role="page"]#PageID').
// Trigger interval
$('.selector').bind('pageinit', function () {
setInterval("window.location.reload();", 5000);
});
// Stop interval when navigating away
$('.selector').bind('pagehide', function () {
clearInterval();
});
How do I ensure that this only occurs on the page from which it is
called rather than it calling it on every page I link to with ajax
based navigation?
Don't call it? Currently your code is set up to always run when it's included on the page. Either don't include it or prevent it from running in some other way (such as an if-statement).
You could clear the interval just before you navigate.
First you need to get a reference to the interval when you create it:
var intervalRef = setInterval("window.location.reload();", 5000);
Then you can clear it like this:
clearInterval(intervalRef);
// Navigate
Just cancel your timeout when the other page loads, or when the current page exits (the other page loads in ajax so the timed interval stays up).
// trigger
myInterval = setInterval("window.location.reload();", 5000);
// stop
clearInterval(myInterval);