what am I doing wrong? I am trying to show bars corresponding to the initial values of the class="likes"
Here is the fiddle
http://jsfiddle.net/sghoush1/VU3LP/40/
The Jquery looks like this
var baractive = $('<div class="barActive"></div');
baractive.appendTo('.bar');
function checkNumber() {
var valueCurrent = parseInt($(".likes").text());
if(isNaN(valueCurrent) || valueCurrent <= 20) {
$(".barActive").css('height', '20px').css('width', '30px').css('background', 'green');
}
if(isNaN(valueCurrent) || valueCurrent <= 60) {
$(".barActive").css('height', '20px').css('width', '80px').css('background', 'green');
}
}
checkNumber();
You need a loop in the checkNumber() function, so that it will check the value of each .likes element and update the corresponding bar.
function checkNumber() {
$(".likes").each(function () {
var valueCurrent = parseInt($(this).text());
if (isNaN(valueCurrent) || valueCurrent <= 20) {
$(this).prev(".bar").children(".barActive").css('height', '20px').css('width', '30px').css('background', 'green');
} else if (isNaN(valueCurrent) || valueCurrent <= 60) {
$(this).prev(".bar").children(".barActive").css('height', '20px').css('width', '80px').css('background', 'green');
}
});
}
FIDDLE
Currently, var valueCurrent = parseInt($(".likes").text()); parses text of all like combined, with result being 2010402060, which is probably not what you want.
I'd change checkNumber function this way:
function checkNumber() {
var bars = $(".bar"),
likes = $(".likes");
likes.each(function (index, like) {
var value = parseInt($(like).text(), 10),
bar = bars.eq(index).find(".barActive");
if (value <= 60) bar.css("width", 80);
if (value <= 20) bar.css("width", 30);
});
}
...and move barActive styles into CSS. Working example at jsFiddle.
Related
I am trying to re-create a color guess game where you click on divs that are random colors and you have to guess which one it asks for. However, when I try to add difficulty by adding more divs using the .append function, the divs do not respond to clicks. I have tried using .on("click", function(){}), and still not working.
$(function() {
var initialTrys = 58;
var difficulty = 9;
//End of Game Settings
var trys = initialTrys;
$("#col").html(getRandomColor());
$("#try").html(trys);
run(difficulty);
cor();
$(".color").on("click", function() {
var thisColor = $(this).css("backgroundColor");
if (trys > 0) {
trys--;
$("#try").html(trys);
} else if (trys === 0) {
$("#alert").html("No More Tries").css("color", "red");
// e.preventDefault();
// return false;
}
console.log("clicked");
if (thisColor == $("#col").html() && trys !== 0) {
$("#alert").html("You Got It!").css("color", "green");
$(this).siblings().addClass("clicked").css("backgroundColor", thisColor);
console.log("correct");
} else {
$(this).addClass("clicked");
}
});
$("#reset").on("click", function() {
trys = initialTrys;
$("#alert").html("");
$("#try").html(trys);
$(".color").each(function() {
$(this)
.addClass("color")
.removeClass("clicked")
.css("backgroundColor", getRandomColor());
});
$("#col").html(getRandomColor());
cor();
});
function getRandomColor() {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var color = "rgb(" + r + ", " + g + ", " + b + ")";
return color;
}
function cor() {
$(".color")
.eq(Math.floor(Math.random() * $(".color").length))
.css("backgroundColor", $("#col").html());
}
$("#diffSlide").on("change", function() {
if ($(this).val() == 0) {
$("#diff").html("Easy").css("color", "green");
$(".colorWrapper").children().remove();
run(difficulty);
} else if ($(this).val() == 1) {
$("#diff").html("Medium").css("color", "orange");
$(".colorWrapper").children().remove();
run(difficulty*2);
} else if ($(this).val() == 2) {
$("#diff").html("Hard").css("color", "red");
$(".colorWrapper").children().remove();
run(difficulty * 3);
}
});
function randColor() {
$(".color").each(function() {
$(this).css("backgroundColor", getRandomColor());
});
}
function run(difficulty) {
for (var i = 1; i <= difficulty; i++) {
$(".colorWrapper").append("<div class='color'></div>");
randColor();
if (i % 3 === 0) {
$(".colorWrapper").append("<br />");
}
}
}
});
Note: When the slider does not move, it works fine it is just when you try to change the difficulty.
It looks like you are not attaching a click handler to the newly appended div when it is appended. Abstract your $(".color").on("click", function() {...} into something like:
function attachClickHandler(){
$(".color").on("click", function() {...} //from ln 10 of your code
}
Then you can call attachClickHandler()on ln 10 as well as after the append in run(). This will attach the click handler both when the code initially runs as well as after the new div is appended.
I think this may work for you.
$(document).on("click", ".color", function(){
})
Right now I have this range element:
<input type="range"
onchange= "calculate();"
id="sumRange"
min="50000"
max="500000"
value="50000"
step= "50000"/>
I want its "step" to change depending on its value. For example, if the value is less than 200000 then step = 5000, if more than 200000 then step= 50000.
How can I do that? Do I create a function with simple "if" statements and make it run onchange of the range?
All example i've seen involve jQuery or something else, can i do this without...that?
See below, change the ranges as needed
function calculate() {
var input = document.getElementById('sumRange');
var val = input.value;
var newStep;
if (val < 100000) {
newStep = 10;
} else if (val < 150000) {
newStep = 20;
} else if (val < 200000) {
newStep = 30;
} else if (val < 250000) {
newStep = 40;
} else {
newStep = 50;
}
input.step = newStep;
}
<input type="range"
onchange= "calculate();"
id="sumRange"
min="50000"
max="500000"
value="50000"
step= "50000"/>
here is what you can do in your calculate function, using jquery
calculate = function() {
if ($('#sumRange').attr('value') < 200000 ) {
$('#sumRange').attr('step',5000);
} else {
$('#sumRange').attr('step',50000);
}
var sumRange = document.getElementById(“sumRange”);
sumRange.oninput = function(){
var value = this.value;
if (value > 20000) {
this.step = 50000;
} else {
this.step=5000;
}
I have number of inputs and I want to set a minimum value of each input section. For example, I have set a minimum input value of 100. So if the value of any input is less than 100 from all the inputs it will show an error. Otherwise if value of all the inputs is greater than or equal to 100 it will show the success message.
In my case if I enter less than value in an input it will show error but with this less value if I enter greater value in other input it show success message.
<div class="color-quantity not-selected-inputs selected-input-wrap">
<input type="text" class="custom_small" name="custom_small" onkeydown="return myFunction(event);">
</div>
<div class="color-quantity not-selected-inputs selected-input-wrap">
<input type="text" class="custom_medium" name="custom_medium" onkeydown="return myFunction(event);">
</div>
<input type="text" class="custom_large" name="custom_large" onkeydown="return myFunction(event);">
</div>
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input', this).each(function () {
total += this.value * 1;
});
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
Please have a look at the code and help me find out the issue
There's a couple of issues.
You should declare total outside the loop otherwise you reset it back to 0 on each iteration.
You should also use a single each() call to loop over a set of elements, as map() is intended to be used to create an array from those elements.
You only need to call parseInt() once when you add the value to total
Your else if condition is redundant and can be replaced by just else, or even a ternary as below.
Try this:
jQuery(function($) {
var total = 0;
$('.selected-input-wrap > input').each(function () {
total += parseInt(this.value, 10);
});
var msg = total >= 100 ? '<p>Success</p>' : '<p>Please select at least 100 for each color</p>';
$(".select-quantity").html(msg);
});
The total variable is looping through all the inputs and only once its returning according to your code. Try closing the each loop after the if-else condition and check once.
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input', this).each(function () {
total += this.value * 1;
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
});
})
You can use the following jquery code :-
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input').each(function () {
total = $(this).val();
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
}
else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
});
});
It may help you.
Try this.
var MIN = 100, value = 0;
jQuery('.selected-input-wrap > input').each(function (idx,el) {
value += parseInt(el.value);
});
if (value < MIN) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else {
jQuery(".select-quantity").html('<p>Success</p>');
}
In My Case i have solved the issue as follows:
var total = 0;
var array_total = new Array();
jQuery('.selected-input-wrap > input').each(function(index, value) {
jQuery( ".right-minimu").remove();
var total = jQuery(this).val();
console.log("Total Value : " + total);
if (total != '') {
var t_array = array_total.push(total);
}
console.log('Total Array : ' + array_total);
});
/******** make array unique *************/
var unique_total = [];
jQuery.each(array_total, function(i, el) {
if (jQuery.inArray(el, unique_total) === -1)
unique_total.push(el);
});
var current_urls = jQuery(location).attr('href');
var rest = current_urls.substr(37, 9); //
var current_urls = jQuery(location).attr('href');
var rest_2 = current_urls.substr(37, 18);
var rest_3 = current_urls.substr(37, 15);
var rest_4 = current_urls.substr(37, 8);
jQuery.each(unique_total, function(key, total) {
for (var i = 0; i <= unique_total.length; i++) {
if(rest == "bracelets") {
if (parseInt(unique_total[i]) <= 99) {
jQuery(".select-quantity").css("display", "block");
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
jQuery( "#order-overview-table table" ).css("display" , "none") ;
jQuery( "#order-overview-table").append("<p class='right-minimu'>Please select at least 100 for each color</p>") ;
jQuery('.btn-cart').removeAttr("onclick");
return false;
} else if (parseInt(unique_total[i]) >= 100) {
jQuery(".select-quantity").css("display", "none");
jQuery('.btn-cart').attr('onClick', 'productAddToCartForm.submit(this);');
jQuery(".select-quantity").html('<p>Products Added</p>').delay(4000);
}
}
The value of !$catalog.hasClass('catalog-fixed') in line 6 is always true
$(window).scroll(function(){
var $catalog = $(".catalog-brief");
var sideTop = $catalog.offset().top;
if (sideTop < 1000){
// always true
if (!$catalog.hasClass('catalog-fixed')) $catalog.addClass("catalog-fixed");
} else {
if ($catalog.hasClass('catalog-fixed')) $catalog.removeClass("catalog-fixed");
}
})
But this works fine
var $catalog = $(".catalog-brief");
var sideTop = $catalog.offset().top;
$(window).scroll(function(){
if (sideTop < 1000){
if (!$catalog.hasClass('catalog-fixed')) $catalog.addClass("catalog-fixed");
} else {
if ($catalog.hasClass('catalog-fixed')) $catalog.removeClass("catalog-fixed");
}
})
Did I make any mistakes?
Try to use window.scrollY instead of the current sideTop. Or $(window).scrollTop() if you want to use Jquery.
$(window).scroll(function(){
var $catalog = $(".catalog-brief");
// if ($(window).scrollTop() < 1000) {
if (window.scrollY < 1000) {
if (!$catalog.hasClass('catalog-fixed')) $catalog.addClass("catalog-fixed");
} else {
if ($catalog.hasClass('catalog-fixed')) $catalog.removeClass("catalog-fixed");
}
});
Can you try this:
var $catalog = $(".catalog-brief");
var sideTop = $catalog.offset().top;
$(window).scroll(function(){
(sideTop < 1000) && ($catalog.toggleClass("catalog-fixed"))
})
See: https://stackoverflow.com/a/11069385/1845408
I want to do a count down and want to show like format as Minutes:Seconds:Milliseconds. I made a count down with jquery plug-in countdown but it shows just Minutes:Seconds format.
Is there any way to make it right?
Many Thanks!
Hi guys I have developed a code for my self use the following code
counter for 20 seconds
var _STOP =0;
var value=1999;
function settimer()
{
var svalue = value.toString();
if(svalue.length == 3)
svalue = '0'+svalue;
else if(svalue.length == 2)
svalue = '00'+svalue;
else if(svalue.length == 1)
svalue = '000'+svalue;
else if(value == 0)
svalue = '0000';
document.getElementById('cn1').innerHTML = svalue[0];
document.getElementById('cn2').innerHTML = svalue[1];
document.getElementById('cn3').innerHTML = svalue[2];
document.getElementById('cn4').innerHTML = svalue[3];
value--;
if (_STOP==0 && value>=0) setTimeout("settimer();", 10);
}
setTimeout("settimer()", 10);
Try this: http://jsfiddle.net/aamir/TaHtz/76/
HTML:
<div id="timer"></div>
JS:
var el = document.getElementById('timer');
var milliSecondsTime = 10000;
var timer;
el.innerHTML = milliSecondsTime/1000;
timer = setInterval(function(){
milliSecondsTime = milliSecondsTime - 1000;
if(milliSecondsTime/1000 == 0) {
clearTimeout(timer);
el.innerHTML = 'BOOOOM';
}
else {
el.innerHTML = milliSecondsTime/1000;
}
},1000);
If you want to make your own timer.
read this earlier question
How to create a JQuery Clock / Timer
Try setting the format parameter - http://keith-wood.name/countdownRef.html#format
On further reading, this plugin doesn't do milliseconds. At this point, you either have to edit the actual plugin code or find a new plugin.
I completely agree with #Matt Ball's comment.It may also cause the browser to crash.
Why don't you try this solution instead
jQuery 1 minute countdown with milliseconds and callback
I did it like this (generic counter from N to X (X > N)):
var dynamicCounterAddNewValue = 20;
var currentDynamicUpdater;
function dynamicCounterForValueForControlUpdater(_updaterData) {
_updaterData.from += dynamicCounterAddNewValue;
if (_updaterData.from > _updaterData.to) {
_updaterData.from = _updaterData.to;
}
_updaterData.c.html(_updaterData.from.toString());
if (_updaterData.from < _updaterData.to) {
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
10,
{
c: _updaterData.c,
from: _updaterData.from,
to: _updaterData.to
}
);
}
else {
clearTimeout(currentDynamicUpdater);
}
return;
}
// _c -> jQuery object (div,span)
// _from -> starting number
// _to -> ending number
function dynamicCounterForValueForControl(_c, _from, _to) {
clearTimeout(currentDynamicUpdater);
dynamicCounterForValueForControlUpdater(
{
c: _c,
from: _from,
to: _to
}
);
return;
}
EDIT: Updated version (more flexible - for N elements one after another):
(input element is Array of elements for making them dynamic-counts)
var dynamicCounterTimeout = 10;
var currentDynamicUpdater;
function odcArray(_odca) {
this.odca = _odca;
return;
}
function odc(_c, _from, _to) {
this.c = _c; // $('#control_id')
this.from = _from; // e.g. N
this.to = _to; // e.g. M => (M >= N)
var di = parseInt(_to / 45, 10);
if (di < 1) {
di = 1;
}
this.dynamicInc = di;
return;
}
function dynamicCounterForValueForControlUpdater(_odca) {
if (
_odca.odca === null
||
!_odca.odca.length
) {
clearTimeout(currentDynamicUpdater);
return;
}
var o = _odca.odca[0];
o.from += o.dynamicInc;
if (o.from > o.to) {
o.from = o.to;
_odca.odca.shift(); // Remove first element
}
o.c.html(o.from.toString());
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
dynamicCounterTimeout,
_odca
);
return;
}
function dynamicCounterForValueForControl(_odca) {
clearTimeout(currentDynamicUpdater);
// SETUP all counters to default
for (var i = 0; i < _odca.odca.length; i++) {
_odca.odca[i].c.html(_odca.odca[i].from.toString());
}
dynamicCounterForValueForControlUpdater(
_odca
);
return;
}