Changing css based on javascript value fetch from API - javascript

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

Related

How can I increase a CSS property's value repeatedly on click?

I want to add (in this case, decrease, technically) the value of an element each time a different element is clicked. What I have so far:
$("#trigger_heritage").click(function () {
$(".heritage_content ul").css("margin-left", + -880);
// So each time clicking shall move the .heritage_content ul-element 880px further left
});
It gets 880px far left, but only once. What I want is that this value gets increased each time the other element gets clicked.
How would I do that?
You can provide a string in the format -=[value] to the css() method which you can use to amend the current value. Try this:
$("#trigger_heritage").click(function () {
$(".heritage_content ul").css("margin-left", '-=880');
});
Working example
Here is a simple example:
$(document).ready(function() {
var move = 0;
$(".left").click(function () {
move -= 25;
$(".move").css("margin-left", move + "px");
});
$(".right").click(function () {
move += 25;
$(".move").css("margin-left", move + "px");
});
})
Fiddle: https://jsfiddle.net/gjfjahjo/
Set a variable, say $marginLeft, and increment this each time the function is called, then set the margin-left:$marginLeft....

Do an action based on presence of ALT attribute with Javascript

I have some javascript which looks at the body and finds words and if one is present, it outputs a div. This is useful for many things, however...
What I need to do is also look at the body and all the ALT tags for the page as well.
I found this: Use javascript to hide element based on ALT TAG only?
Which seems to change the ALT attribute, however I want to perform an action.
Here's my JS so far.
var bodytext = $('body').text();
if(bodytext.toLowerCase().indexOf('one' || 'two')==-1)
return;
var elem = $("<div>Text Here</div>");
Thank you.
P.S. I am a N00B/ relatively new at JS, I am doing this for a small project, so I am not sure where to start for this in terms of JS functions.
Updated Answer
Try this out, I commented the code to explain it a bit.
// build array of triggers
var triggers = ['trigger1','trigger2','trigger3'];
// wait for page to load
$(function() {
// show loading overlay
$('body').append('<div id="mypluginname-overlay" style="height:100%;width:100%;background-color:#FFF;"></div>');
// check page title
var $title = $('head title');
for(trigger of triggers) {
if($($title).innerHTML.toLowerCase().indexOf(trigger) >= 0) {
$($title).innerHTML = '*censored*';
}
}
// check all meta
$('meta').each(function() {
var $meta = $(this);
for(trigger of triggers) {
if($($meta).attr('name').toLowerCase().indexOf(trigger) >= 0) {
censorPage();
return; //stop script if entire page must be censored
} else if($($meta).attr('content').toLowerCase().indexOf(trigger) >= 0) {
censorPage();
return; //stop script if entire page must be censored
}
}
});
// check all img
$('img').each(function() {
var $img = $(this);
for(trigger of triggers) {
if($($img).attr('alt').toLowerCase().indexOf(trigger) >= 0) {
censor($img);
}
}
});
// check all video
$('video').each(function() {
var $video = $(this);
for(trigger of triggers) {
if($($video).attr('alt').toLowerCase().indexOf(trigger) >= 0) {
censor($video);
}
}
});
// if you want to be extra careful and check things like background image name,
// you'll have to run this code here - very inefficent
// but necessary if you want to check every single element's background image name:
for($element of $('body').children()) {
for(trigger of triggers) {
if($($element).css('background-image').toLowerCase().indexOf(trigger) >= 0) {
$($element).css('background-image','');
}
}
}
, function() { // Not sure if this is totally correct syntax, but use a callback function to determine when
// when the rest of the script has finished running
// hide overlay
$('#mypluginname-overlay').fadeOut(500);
}});
function censor($element) {
// just a basic example, you'll probably want to make this more complex to overlay it properly
$element.innerHTML = 'new content';
}
function censorPage() {
// just a basic example, you'll probably want to make this more complex to overlay it properly
$('body').innerHTML = 'new content';
}
---Original Answer---
I'm not sure exactly what you would like to do here, you should add more detail. However if you choose to use jQuery, it provides tons of useful methods including the method .attr(), which lets you get the value of any attribute of any element.
Example:
var alt = $('#my-selector').attr('alt');
if (alt == 'whatYouWant') {
alert('yay');
} else {
alert('nay');
}
You're using jQuery lib, you could select elements by attribute like:
$('[alt="one"]').each(function(el){
// do something
var x = $(el).arrt('alt');
});
If you use selector $('[alt]') you can get elements that have this attribute set, and then check the value of the element if you have a more complicated selection.
Than you have to change your return, as you could not put a div inside an ALT tag, it didn't work.
Here is about what is your expected output.
UPDATE
As you want to change all images and video in a page, the way to do this with jquery is through $.replaceWith():
$('img,video').replaceWith($('<div>Text Here</div>'));
If you need to filter the elements:
$('img,video').each(function(el){
if($(el).prop('tagName') == 'IMG' &&
$(el).attr('alt') == 'the text...') {
$(el).replaceWith($('<div>Text Here</div>'));
}
})
But I'm not an expert on Chrome Extensions, I just put this code here in jQuery, as you was using jQuery.
Of course it could be done, with much code with plain javascript and the DOM API.

How to execute jquery when a variable with a CSS property changes

I need to set the scrollleft back to 0 on my wrapper when a specific css property changes. I'm a bit new to jquery and have never used variables, but I'm assuming that I'll need to declare the somewhat complex variable before the function, and then execute the function when the variable changes. Am I correct? It needs to continually respond like this to resize queries. This will be an epic solution for me if it works!
var changer = $(".dummy").css("float"); //whatever the float property is
$(document).ready(){
$(window).resize(function(){
if ($(".dummy").css("float") != changer ){
$(".wrapper").scrollLeft(0);
}
});
here is my suggestion: Use an ID for "dummy", if you have more than one "dummy" in your dom-tree you get an array with html elements from jquery.
$(document).ready(function() {
// First init for "dummy"
var $dummy = $("#dummy"),
dummyFloat = $dummy.css("float");
$(window).resize(function () {
var dynamicDummyFloat = $dummy.css("float");
if (dynamicDummyFloat != dummyFloat) {
$(".wrapper").scrollLeft(0);
dummyFloat = dynamicDummyFloat;
}
});
});
The code that you have written will work fine.

jQuery getting tag's content dynamically

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
}
});

How do i call a spcific jquery function form within another function?

I have the following code which is not working
jQuery
jQuery(window).bind("load", function() {
function effects(content_name,active_name)
{
// switch all tabs off
$(active_name).removeClass("active");
// switch this tab on
$(this).addClass("active");
// slide all content up
$(content_name).slideUp();
// slide this content up
var content_show = $(this).attr("title");
$("#"+content_show).slideDown();
}
$("a.tab_1").click(function () {
var content_name = '.content_a';
var active_name = 'a.tab_1.active';
effects(content_name,active_name);
});
$("a.tab_2").click(function () {
var content_name = '.content_b';
var active_name = 'a.tab_2.active';
effects(content_name,active_name);
});
$("a.tab_3").click(function () {
var content_name = '.content_c';
var active_name = 'a.tab_3.active';
effects(content_name,active_name);//create effects with the content
});
});
Its a set of tab groups upto 8 in number. Writing individual functions will have an adverse effect on loading time.
Answer 2 hours later:
Thank you all for pointing out the "effetcs" mistake in the code.
The other mistake was I was doing was not passing "$(this)" as a parameter into the called function "effects".
I Have adjoined the link where the necessary changes are done and the code works.
[jsfiddle] http://jsfiddle.net/phyGS/2/
Replace effetcs with effects at the first block, and replace every occurrence of
effects(content_name,active_name);
with
effects.call(this, content_name, active_name);
This call method assigns a new value to the this property of function effects.

Categories