First of all, I know my question seems to be already asked many many times but I'm facing a weird issue.
Here's the situation :
I've got an integer (dynamically loaded) in this tag :
<i id="my_id">{{here's my integer}}</i>
What I want to do is to retrieve the integer inside my tag but this integer is set to 0 at first (When the page isn't fully loaded") and then 2 or 3 seconds later, this integer is set to its real value.
So I tried something like this :
var test = 0;
$('#my_id').change(function(){
test = $('#my_id').html();
});
console.log(test);
This always returns me 0. I tried many things to get the current value of my tag but I can't find a way to succeed. Can you please help me get this integer ?
Cordially, Rob.
The change event is only fired by input elements. You can try polling the value like so:
var intervalId = setInterval(function() {
var value = parseInt($('#my_id').text(), 10);
if(value > 0) {
clearInterval(intervalId);
//... do stuff
}
}, 250); //poll every 250ms
Another way is to fire a custom event when you change the value:
//Somewhere in your code where you set the value in the i tag:
$('#my_id').text(value);
$('#my_id').trigger("valueChanged");
//Elsewhere in your code
$('#my_id').on("valueChanged", function() {
var value = parseInt($(this).text(), 10);
if(value > 0) {
//... do stuff
}
});
Related
I have this code below that returns an updated value from an API every seconds in an html span tag:
$(document).ready(function(){
setInterval(function(){
$.get('https://api.kraken.com/0/public/Ticker?pair=XXBTZEUR', function(data){
var kraken_btc_eur = data.result.XXBTZEUR.c[0]
$("#kraken_btc_eur").text(kraken_btc_eur);
});
}, 1000);
});
How can I change the css of the <span id="kraken_btc_eur"> depending on whether the value of the variable var kraken_btc_eur changes from a prior value.
I figure I must include an IF statement, create a new variable to compare to the old update and clear the variable for this to be executed in the next second again PLUS different ID for up or down. I am not sure how to implement that.
Thanks all for your guidance.
Try something like:
$(function() {
var kraken_btc_eur_old = 0;
setInterval(function(){
$.get('https://api.kraken.com/0/public/Ticker?pair=XXBTZEUR', function(data){
var kraken_btc_eur = data.result.XXBTZEUR.c[0];
if (kraken_btc_eur_old != kraken_btc_eur) {
// Change css
}
kraken_btc_eur_old = kraken_btc_eur;
$("#kraken_btc_eur").text(kraken_btc_eur);
});
}, 1000);
});
Comparing current to new...
Something like:
if(kraken_btc_eur !== $("#kraken_btc_eur").text()) {
// if different change background and add new text
$("#kraken_btc_eur").css('background', 'red').text(kraken_btc_eur);
}
This way you only update if different, no point updating something with the same value
I have a table with games detail. and I want to add a countdowntimer for every game.
I'm using the jquery-countdownTimer plugin
My Html:
<span class="given_date" data-gamestart="2016/3/11 15:30"></span>
<span class="given_date" data-gamestart="2016/3/13 18:00"></span>
<span class="given_date" data-gamestart="2016/3/15 17:45"></span>
<span class="given_date" data-gamestart="2016/3/22 19:45"></span>
and i user a this plugin to make the count down.
My js:
$('.given_date').countdowntimer({
dateAndTime : "2016/3/10 17:05"
});
A jsFiddle example
My issue is, even though I provide a different time for each span, all of the timers show the same value and countdown in sync
Why does each span not show it's own timer based on my provided values?
Your issue is that your elements do not have ids.
This plugin uses the below code to set the timers then display their values. Note the window['regexpMatchFormat_' + $this.attr('id')]. This uses the id of each element to create a unique global variable to keep track of the timers. If your elements have no ids, you end up repeatedly overwriting your first timer
//Code for starting the timers.
if (options.regexpMatchFormat != undefined && options.regexpReplaceWith != undefined && options.timeSeparator == undefined) {
window['regexpMatchFormat_' + $this.attr('id')] = options.regexpMatchFormat;
window['regexpReplaceWith_' + $this.attr('id')] = options.regexpReplaceWith;
}
//Function for displaying the timer.
function html($this, content) {
var processedContent = content;
if (typeof window['regexpMatchFormat_' + $this.attr('id')] !== 'undefined' &&
typeof window['regexpReplaceWith_' + $this.attr('id')] !== 'undefined') {
var regexp = new RegExp(window['regexpMatchFormat_' + $this.attr('id')]);
processedContent = content.replace(regexp,
window['regexpReplaceWith_' + $this.attr('id')]);
}
$this.html(processedContent);
}
Working jsFiddle
This is why you should always link to the plugin you are using ;)
The best way is to loop through the spans with jQuery's .each() and set up the countdowntimer within that loop. Something like this:
$('.given_date').each(function() {
$(this).countdowntimer({
dateAndTime : this.getAttribute("data-gamestart")
});
});
I wrote simple monitor which check few things on my networks and display status - I am fetching statuses using ajax.
When something is wrong I am adding class error to div which is displaying current status.
Later I add player with error sound when class error is present it plays music. I set 3 second interval and thats all.
But not always error mean error, sometimes I recive false warning.
Now I am looking for way to play sound when class error exists longer than XX seconds.
I suppose I have to wrote function with interval 1s, add every hit 1 to temp variable and check is variable bigger than else clean temp variable, but maybe is there more elegant way.
i guess it should work
$('.error').each(function(){
var e = $(this)
setTimeout(function(){
if (e.attr('class') == 'error'){
e.attr('class','error-with-sound');
}
},2000);
});
You should take two vars store the current time at their respective events.
var oldTime, newTime;
// Now when you are adding the class
$(something).addClass("someclass");
oldTime = new Date().getTime(); // Store the timestamp.
//And when you are removing the class
$(something).removeClass("someclass");
newTime = new Date().getTime(); // Store the timestamp.
// Now you check whether class was added for more then XX Seconds
var _diff = (newTime - oldTime)/1000; // Diference is in seconds.
There is no direct way for that, you can add timestamps in your class with separator something like error_1448953716457 and later you can split that and can compare with current timestamps
$('#na').click(function () {
var t = new Date().getTime();
$('h1').addClass("error_" + t);
});
$('#nr').click(function () {
var t = new Date().getTime();
$("[class^=error]").each(function (e) {
$("span").html("Diff. Seconds : " + ((t - ($(this).attr('class').split(' ').pop().split('_')[1])) / 1000).toString());
});
});
input {
width:100px;
}
.error {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<h1>.addClass()</h1>
<input id="na" value="Add Class1" type="button" />
<br/>
<input id="nr" value="Calculate Diff" type="button" />
<span></span>
If you want to track .error elements on the page, set an independent interval that looks for those elements and tracks the ones it has seen before by setting an attribute or data value in jquery.
Remember to clearInterval(interval) if you no longer need to check for .error elements.
(function ($) {
// set constants in milliseconds as desired
var INTERVAL_LENGTH = 100, // how often to check DOM for error elements
NOTIFY_AFTER = 3000; // handle error after this length
// check for .error elements and handle those that have been around for a while
var interval = setInterval(function () {
var now = Date.now();
$(".error").each(function () {
var t = $(this).data('error-time');
if(t) {
if(now - t > NOTIFY_AFTER) {
handleErrorElement(this);
}
}
else {
$(this).data('error-time', now);
}
});
}, INTERVAL_LENGTH);
function handleErrorElement(elem) {
// do what you need for error elements visible past a threshold
console.log("handling error element: ", elem);
}
})(jQuery);
I want to create a website with multiple countdowns activated by a click, some of them have different time, others the same. I need to organize them depending the time left. When one finish I need to return it to his original countdown value, so you can click again.
To understand better (I don't need the effects, I made them only for the example): http://i.imgur.com/lvcwbqm.gif
I have this: http://jsfiddle.net/m19aojmu/
Each countdown works independently of the others.
HTML
<div class="element" id="el1"><b>Elm 1</b> <span class="timeout">10</span> segundos</div>
<div class="element" id="el2"><b>Elm 2</b> <span class="timeout">100</span> segundos</div>
<div class="element" id="el3"><b>Elm 3</b> <span class="timeout">5</span> segundos</div>
Javascript
function timer(selector) {
var self = $(selector);
var sec = parseInt(self.find('span.timeout').text());
var interval = setInterval(function() {
sec--;
if (sec >= 0) {
self.find('span.timeout').text(sec);
} else {
clearInterval(interval);
}
}, 1000);
}
$("body").on('click', '.element', function() {
timer(this);
});
While each countdown have a different id (el1, el2, el3 ...) I don't know to detect which of them finished, therefore I don't know how to add a class when it start and end.
About the ubication, what should I do? Different classes for each location with position absolute?
I know it's a lot, but some help will be great.
Thank you very much.
Agusitn you code its like 95% correct, but you are setting the .text() into the sec variable wich is 0 or -1
Lets change the code a little bit
First lets take the actual value of the span DOM Element.
var actualTime = $('span.timeout').html();
console.log("the actual value when click is " + actualTime)
Later on the if statement we check when the actual span text its equal to 0
else if($(this).find('span').text() <= 0) {
console.log(sec)
var text = self.find('span.timeout').text(actualTime);
console.log(actualTime)
clearInterval(interval);
}
and when the .text() its === to 0, we set the actualTime variable to get back to the actual time.
here is the JsFiddle
I'm making a webpage where user events are logged in.
To test the feature I made a small, independant webpage with a teaxtarea and a text input. The events logged are those performed on the input element.
I want to prevent the same event text to be shown multiple times in a row, but I can't seem to prevent them from showing up!
I also want to add a line to separate event groups 0.5 seconds after no other event happened, but the line seems to appear on every event trigger, evenif I use clearTimeout with the timeout ID.
Basically: I don't want any line to be repeated. If the last line is a separator line, then it must not add another one. Yet it doesn't see to work.
JSFiddle Demo
Here is my code:
JavaScript
var timerID = 0;
function addSeparateLine()
{
document.getElementById('listeEvenements').value += "--------------------\n";
}
function show(newEventText)
{
var eventListField = document.getElementById('listeEvenements');
var eventList = [];
if (eventListField.value.length > 0)
{
eventList = eventListField.value.split("\n");
}
var eventCounter = eventList.length;
if (eventList[eventCounter - 2] == newEventText)
{
clearTimeout(timerID);
newEventText = "";
}
timerID = setTimeout(addSeparateLine, 500);
if (newEventText !== "")
{
eventListField.value += newEventText + "\n";
}
return true;
}
HTML
<fieldset id="conteneurLogEvenements">
<legend>Events called from HTML attribute</legend>
<textarea id="listeEvenements" rows="25"></textarea>
<input id="controleEcoute" type="text" onBlur="show('Blur');" onchange="show('Change');" onclick="show('Click');" onfocus="show('Focus');" onMousedown="show('MouseDown');" onMousemove="show('MouseMove');" onMouseover="show('MouseOver');" onkeydown="show('KeyDown');"
onkeypress="show('KeyPress');" onkeyup="show('KeyUp');" />
</fieldset>
http://jsfiddle.net/z6kb4/2/
It sounds like what you want is a line that prints after 500 milliseconds of inactivity, but what your code currently says to do is "print a line 500 milliseconds after any action, unless it gets canceled". You can get better results by structuring the code more closely to your intended goal.
Specifically, instead of scheduling a new timeout every time an event occurs, simply start a loop when the first event occurs that checks the time that has elapsed since the most recent event received and then prints a line when the elapsed time exceeds the desired threshold (500 milliseconds). Something like:
function addSeparateLine() {
var elapsed = new Date().getTime() - lastEventTime;
if (elapsed >= 500) {
document.getElementById('listeEvenements').value += "--------------------\n";
clearInterval(timerID);
timerID = -1;
}
}
...and then you schedule it like:
if(newEventText !== "") {
lastEventTime = new Date().getTime();
eventListField.value += newEventText+"\n";
if (timerID == -1) {
timerID = setInterval(addSeparateLine,100);
}
}
Working example here: http://jsfiddle.net/z6kb4/4/
Because you are not actually stopping the show function in any way. The clearTimeout only applies to the separator add. I have updated your fiddle. You need to wrap your function with
if (+new Date() - lastfire < 500) return;
and
lastfire = +new Date();
(before the last return--see the updated fiddle). Also, make sure to stick the global definition var lastfire = -1; somewhere up top.