Trying to get this javascript to read the value of the div "flow-hold" and change the background color based on the value.
I have a div named flow hold with a value of 132 for example, that I would like to see green because it is less than the 200 threshold. If the value exceeds the threshold, I would like it to be red.
<div class="flow-hold">132</div>
<script type="text/javascript">
$('.flow-hold'), function(){
if($(this).val()>=200){
$('.flow-hold').css({"background-color":"red"});
} else {
$('.flow-hold').css({"background-color":"green"});
}
});
</script>
try this simple and easy:
$('.flow-hold').each(function() {
if (parseInt($(this).text()) >= 200) {
$(this).css("background-color","red");
} else {
$(this).css("background-color","green");
}
});
If you want to do it on page load you could use your Back-End technology to assign a CSS class with demanded color according to the threshold.
For example, in PHP it would be:
<div class="flow-hold <?=($threshold>=200)?'bg-red':'bg-green'?>">132</div>
In your CSS file:
bg-red{
background-color: red;
}
bg-green:{
background-color: green;
}
However, if you want to do it on client-side, you have to allocate an exact action to it, for instance:
<div class="flow-hold">132</div>
<script type="text/javascript">
$('.flow-hold').on('hover', function(){
if($(this).val()>=200){
$('.flow-hold').css({"background-color":"red"});
} else {
$('.flow-hold').css({"background-color":"green"});
}
});
</script>
actually your problem are the accessors that you are using. check that if you use JQuery and get the items by class you will get an array with all the divs containing that class.
so here you have a working example of what you wanted to achieve taking into account what I told before.
NOTE: your code doesn't run by itself, next time please fix it.
NOTE2: note that I didn't do a lot of changes and it started to work.
function changeBackground() {
let div = $('.flow-hold')[0];
if (div.innerText >= 200) {
$('.flow-hold').css({
"background-color": "red"
});
} else {
$('.flow-hold').css({
"background-color": "green"
});
}
}
changeBackground();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flow-hold">132</div>
You can use the script below:
$(document).ready(function(){
var value = parseInt($('.flow-hold').html());
if(value >= 200){
$('.flow-hold').css("background-color","red");
}
else {
$('.flow-hold').css("background-color","green");
}
});
I believe you intended to use the .each( function ) jQuery method, where the function should only handle one element at a time, so it shouldn't lookup $('.flow-hold') again, since there can be more than one element with that class.
You should also use the .text() method, not the .val() method.
$('.flow-hold').each(function() {
if ($(this).text() >= 200) {
$(this).css({"background-color":"red"});
} else {
$(this).css({"background-color":"green"});
}
});
Since you are setting the same property in both cases, you can also use the implicit looping of the .css( propertyName, function ) method:
$('.flow-hold').css("background-color", function() {
return ($(this).text() >= 200 ? "red" : "green");
});
Related
I am trying to understand how javascript (jquery in this case) if statements work. I thought i understood but i don't fully get some things. Please see the code below. Why is it when i click on the element with the class of "cat" that it does not remove the class of "black" and add the class of "red".
$(function() {
var cat = true;
$( ".cat" ).click(function() {
cat = false;
});
if (cat === true) {
$('.cat').removeClass('red').addClass('black');
} else {
$('.cat').removeClass('black').addClass('red');
}
});
i know there is probably a very simple answer to this but i'm just learning so any help would be appreciated, thanks in advance.
Toggle the value of cat and put the if block inside the function that you want to bind with the event 'click':
$(".cat").click(function() {
cat = !cat;
if (cat === true) {
$('.cat').removeClass('red').addClass('black');
} else {
$('.cat').removeClass('black').addClass('red');
}
});
Edit: Simpler way to do this is to use .toggleClass():
$(".cat").click(function() {
$(this).toggleClass('red black');
});
If you want to check on click, put the if inside the click event. The reason why your solution doesn't work is because you attach a listener to the element, but you immediately do a check. The check doesn't happen every time the user clicks, just once. You must put it in the listener's callback function so it executes every time the element is clicked:
$(function() {
$(".cat").click(function() {
$(".cat").toggleClass("black red");
});
});
How this works is it attaches a click event to .cat and, on click, toggles the classes black and red. This completely gets rid of the checking because that isn't necessary. Just toggle the classes on click. Also, no need to repeat the selector, just use this. Here's a snippet:
$(function() {
$(".cat").click(function() {
$(this).toggleClass("black red");
});
});
.black {
color: black;
}
.red {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat red">Test</div>
Your code is not removing class black and adding class red because your if(){}else{} code block running when your page is loading. When you are clicking the cat class it is only assigning the value of cat variable to false. since your if else code block is out of your click function that is why it is not executing again. and that is why it is not working. To work your code place your if else code block in the click function like this:
$( ".cat" ).click(function() {
cat = false;
if (cat === true) {
$('.cat').removeClass('red').addClass('black');
} else {
$('.cat').removeClass('black').addClass('red');
};
});
I have a checkbox and some <div>s that show/hides whenever a checkbox is checked. Now it all works great but it could be more efficient.
jQuery("#filtertype").change(function () {
if (jQuery("#posttype").is(":checked")) {
jQuery("#postblock").slideDown("slow");
} else {
jQuery("#postblock").slideUp("slow");
}
if (jQuery("#taxonomycat").is(":checked")) {
jQuery("#taxonomyblock").slideDown("slow");
} else {
jQuery("#taxonomyblock").slideUp("slow");
}
if (jQuery("#taxonomytag").is(":checked")) {
jQuery("#taxonomyblocktag").slideDown("slow");
} else {
jQuery("#taxonomyblocktag").slideUp("slow");
}
if (jQuery("#fieldjeskey").is(":checked")) {
jQuery("#fieldblock").slideDown("slow");
} else {
jQuery("#fieldblock").slideUp("slow");
}
if (jQuery("#sliderme").is(":checked")) {
jQuery("#sliderblock").slideDown("slow");
} else {
jQuery("#sliderblock").slideUp("slow");
}
});
This works like it should; it gets the ID of the checkbox <input> and for every <input> (#filtertype, #taxonomycat etc.) it will show or hide a <div> (#postblock, #taxonomyblock etc.)
It may be smarter to get the ID of every <input> and toggle the slideUp, slideDown function.
How can this be done?
Firstly, rather than have a list of id selectors, put a single class of each of those checkboxes, along with a data attribute to specify the relation. Something like this:
<input type="checkbox" name="posttype" class="filter-checkbox" data-rel="postblock" value="foobar" />
Then in javascript you can simplify all the code above to the following:
jQuery("#filtertype").change(function() {
$('.filter-checkbox').each(function() {
var func = this.checked ? 'slideDown' : 'slideUp';
$('#' + $(this).data('rel'))[func]('slow');
});
});
Example fiddle
It could be more efficient by not using jQuery.
Replace all of your jQuery("#someID").is(":checked") with
document.getElementById('someID').checked, and short of writing your own lightweight animation engine that's as good as you'll get.
Or you can go down the dark path of obscurity:
jQuery("#postblock")["slide"+(document.getElementById('posttype').checked ? "Down" : "Up")]("slow");
But that's probably not a good idea :p
I have simple Chrome extension that injects some html into a game webpage that lets a user customize the background image of the webpage. It stores the URL of the image with setlocalstorage so that when they return to the game the custom background image is still there. I've included some CSS that forces the image to fit the width of the browser window. This satisfies most users but, there are a few that have requested I allow them to turn off the width-matching feature. What I'd like to do is add a check box to allow the user to turn off the width adjustment.
I'm thinking some sort of "if the box is checked apply this class to the body tag" sort of thing but, I can't seem to figure it out.
If someone could show me how to accomplish this I'd really appreciate it!
Attach an onchange event listener to the checkbox that checks the value of 'checked' for your checkbox element and adds/removes the class:
yourCheckboxElement.addEventListener('change', function(e){
document.body.classList[this.checked ? "add" : "remove"]("someClass");
/* save value of this.checked to localStorage here */
});
jsFiddle example: http://jsfiddle.net/8RC2m/1/
Change css when checkbox is marked:
$("#new").click(function() {
if (this.checked){
$(this).closest('p').addClass('white');
} else {
$(this).closest('p').removeClass('white');
}
});
add styles:
.white {
color: white;
}
That might work for you, no?
Additionally,
$(":checkbox").attr("autocomplete", "on");
Wrap your width adjustment code in a css class like width-adjustment. Then try something like this:
if ($('#IdOfYourCheckBox').is(":checked") == true){
$("#ElementToChange").removeClass('width-adjustment');
}
You have requested JavaScript only so i will avoid jQuery, try something like this:
var b = document.getElementsByTagName("body")[0];
if (document.getElementById('checkbox-id').checked){
b.className +=" yourclass";
}
hope it helps
You can use this script to check if the chkbox is checked or not.
(function( $ ){
$.fn.check = function( handler ) {
if (handler) {
this.each(function() {
$(this).change(function() {
if ($(this).attr('checked')) {
handler.call(this);
$(this).closest('p').addClass('white');
}
});
});
} else {
this.each(function() {
$(this).attr('checked', true);
$(this).change();
$(this).closest('p').addClass('white');
});
}
};
$.fn.uncheck = function( handler ) {
if (handler) {
this.each(function() {
$(this).change(function() {
if (!$(this).attr('checked')) {
handler.call(this);
$(this).closest('p').removeClass('white');
}
});
});
} else {
this.each(function() {
$(this).attr('checked', false);
$(this).change();
$(this).closest('p').removeClass('white');
});
}
};
})( jQuery );
I am pretty new to jQuery but I am trying to get a code setup which hides a div when the 'innerHTML' is null. I tried using the code below. But it doesn't work! Where is my fault??
if (($("#php-errors").html).length) {
$("#php-errors").css("display", "block");
}
else {
$("#php-errors").css("display", "none");
}
One line, and using .show() and .hide() methods:
var hasCont = $("#php-errors").contents().length ? $("#php-errors").show() : $("#php-errors").hide();
Using the ternary operator that says:
(define var) statement ?
action if statement is true :
action if statement is false ;
DEMO JSFIDDLE
A good practice would be to cache your element inside a var, let's call it var $el, and use it like:
var $el = $("#php-errors");
var hasCont = $el.contents().length ? $el.show() : $el.hide();
Much more readable, and
it will save you some micro processing time ;) but it really helps in terms of cross-function reusability (if defined outside the function.)
if ($("#php-errors").html().length) {
$("#php-errors").css("display", "block");
}
else {
$("#php-errors").css("display", "none");
}
Correction:
($("#php-errors").html).length should be $("#php-errors").html().length
You can clean your code a little like this.
It also uses the innerHTML property as the condition part of the ternary expression. If there's any content, it'll return and set "block", if not, then "none".
$("#php-errors").css("display", function() {
return this.innerHTML ? "block" : "none";
});
http://jsfiddle.net/WKWNc/2/
update:
If this only runs when the page loads, you could initially have it set to "block", and then do this.
$("#php-errors:empty").hide();
http://jsfiddle.net/WKWNc/1/
Or the opposite, have it set to "none", and show it if not empty.
$("#php-errors:not(:empty)").show();
http://jsfiddle.net/WKWNc/
Just to add the css way that will not require javascript in case someone else needs it:
.php-errors:empty { display: none; }
Will Match:
<div class="php-errors"></div>
<div class="php-errors"><!-- test --></div>
Will Not Match:
<div class="php-errors"> </div>
<div class="php-errors">
<!-- test -->
</div>
<div class="php-errors">
</div>
Source: https://css-tricks.com/almanac/selectors/e/empty/
For your case, it seems you just want:
$("#php-errors").toggle();
I can see no case where you want to set the display to either block or none if none is already set.
Are you sure your logic isn't redundant?
I think u missed compare , try this
if ($("#php-errors").html() == "") {
$("#php-errors").css("display", "block");
}
else {
$("#php-errors").css("display", "none");
}
I would do something like this:
var $php_errors = $("#php-errors");
if ($php_errors.is(":empty")) {
$php_errors.hide()
}
else {
$php_errors.show();
}
hope it helps
<div class="example">
Test
</div>
$('.example').click(function(){
$(this).css('color','red');
});
When the code above get's clicked, it will apply the .css. Now what I need is for another bit of code (let's say $(this).css('color','blue');) to be applied, replacing the previous code when .example gets clicked a second time.
I've searched for this and askers seem to only need .show/.hide events which can be substituted with .toggle, which is obviously not the case here.
Since you may have many instances of class example, simply maintaining a state using a single variable is not feasible, what you can do is to maintain the state of each instance of example within itself:
Define two css classes
.example { background:blue }
.example.red { background:red }
Then your click method:
$('.example').click(function(){
$(this).toggleClass('red');
});
If you prefer not to define new css classes, you can use data(), to make sure that the state is exclusive within each .example, this is useful if you have many instances of .example
$('.example').click(function() {
var color = $(this).data('color');
if(color != 'blue') {
$(this).css('color', 'blue');
$(this).data('color', 'blue');
} else {
$(this).css('color', 'red');
$(this).data('color', 'red');
}
});
http://api.jquery.com/data/
Something like this would work to toggle between 2 colours (or styles).
$('.example').click(function(){
if($(this).css('color') == "red")
{
$(this).css('color','blue');
}
else
{
$(this).css('color','red');
}
});
<div class="example">
Test
</div>
just maintain a bool and you are done..
var isRed=false;
$('.example').click(function(){
if(isRed)
{
$(this).css('color','blue');
isRed=false;
}
else
{
$(this).css('color','red');
isRed=true;
}
});
Use addClass and removeClass
.blueColor
{
background-color: blue;
}
.redColor
{
background-color: red;
}
And use in your javascript the addClass and removeClass functions:
<script>
$(document).ready(function(){
$(".example").keypress(function() {
if($(".example").val().length > 0)
{
$(".example").addClass("redColor");
}
else {
if($(".example").val().length == 0)
{
$(".example").addClass("blueColor");
$(".example").removeClass("redColor");
}
}
});
});
</script>
I guess you need something more generic about click event exactly so I'd suggest you to use data method to leave the flags
$('.example').click(function() {
if (!$(this).data("custom-even")) {
// odd execution
$(this).data("custom-even", true)
} else {
// even execution
$(this).data("custom-even", false)
}
});
$('.example').click(function(){
var theExample = $(this);
if(theExample.hasClass("clicked")){
theExample.css('color','blue').removeClass("clicked");
}else{
theExample.css('color','red').addClass("clicked");
}
});
http://jsfiddle.net/SnDgh/
Hiya Try this with toggle :)) http://jsfiddle.net/FVXAZ/
SO you can use toggle with your css and every second click will have the vice-a-versa affect. :)
Code
$(function() {
$('.example').toggle(function() {
$(this).css('color','red');
}, function() {
$(this).css('color','blue');
});
});
Have a nice man man, cheers!
Try this:
$('.example').click(function(){
if($('.example').data('isAlreadyClicked')=='true')
{
$(this).css('color','blue');
$('.example').data('isAlreadyClicked','false')
}
else
{
$(this).css('color','red');
$('.example').data('isAlreadyClicked','true')
}
});
Use the one method to handle one-time event binding is a good choice, however this solution will stop all events binded after this code, it may cause inconsistency.
$('.example')
.one('click', function(e) {
e.stopImmediagePropagation();
})
.on('click', function() {
$(this).css('color', blue');
});
Lot of answers all defining a single solution.
Basically, there are two ways that you should use. The other ways mentionned are either unperformant or unsemantic (using data for this kind of solution is overkill). Here are the two ways you may use:
// Toggle a class 'red' defined in your stylesheet
$('.example').on('click', function() {
$(this).toggleClass('red')
})
// Toggle the color with an "if" check
$('.example').on('click', function() {
if (this.style.color === 'red') { // using jQuery is not required
this.style.color === 'blue'
}
else {
this.style.color === 'red'
}
})
You can write:
$('#id').toggle(function() {
$('.css').css('color','red');}
,function() { /////////the second click
$('.css').css('color','blue');}
);