Javascript- Dynamic variable loop - javascript

I'm trying to reduce the amount of code I repeat.
Currently I have the below:
var item1H = $(".item-1").height();
var item1W = $(".item-1").height();
$(".item-1 .text").css('margin-left', -item1W/2);
$(".item-1 .text").css('margin-bottom', -item1H/2);
var item2H = $(".item-2").height();
var item2W = $(".item-2").height();
$(".item-2 .text").css('margin-left', -item2W/2);
$(".item-2 .text").css('margin-bottom', -item2H/2);
I'm looking to put this into a for loop where the variable number would count up to whatever number I needed it to stop.

You can make function like this and use whenever you want
toSetMargin(".item-2")
toSetMargin(".item-2")
function toSetMargin(objStr){
var widthTmp = $(objStr + ' .text').height();
var heightTmp = $(objStr + ' .text').height();
obj.css('margin-left', -widthTmp/2);
obj.css('margin-bottom', -heightTmp/2)
}
This code not impact any other code.

You could use $('[class^="item-"]') to get all the elements that have a class that starts with item-, and the loop over them
$('[class^="item-"]').each(function(){
var $elem = $(this);
var item1H = $elem.height();
var item1W = $elem.width();
$elem.find('.text').css({'margin-left': -item1W/2,'margin-bottom':-item1H/2});
});

Ooh boy, one of these problems. This should help (untested):
for(i=1;i<=STOPPING_NUMBER;i++){
window["item"+i+"H"] = $(".item-"+i).height();
window["item"+i+"W"] = $(".item-"+i).width(); //Was height, accident?
$(".item-"+i+" .text").css('margin-left', 0-window["item"+i+"W"]/2); //Hope this works lol
$(".item-"+i+" .text").css('margin-bottom', 0-window["item"+i+"H"]/2);
}

Guessing these lines:
var item1W = $(".item-1").height();
var item2W = $(".item-2").height();
Should have been:
var item1W = $(".item-1").width();
var item2W = $(".item-2").width();
You could do something like:
function setCSS(item,attr,val) {
$(item +" .text").css(attr, (val * -1)/2);
}
var i, max = 10;
for(i=1;i<=max;i++) {
setCSS(".item-"+ i,"margin-left",$(".item-"+ i).width());
setCSS(".item-"+ i,"margin-bottom",$(".item-"+ i).height());
}
Or something less flexible within the function:
function setCSS(item,w,h) {
$(item +" .text").css("margin-left", (w * -1)/2);
$(item +" .text").css("margin-bottom", (h * -1)/2);
}
var i, max = 10;
for(i=1;i<=max;i++) {
setCSS(".item-"+ i,$(".item-"+ i).width()),$(".item-"+ i).height());
}

Something like this should be pretty acceptible in your case, I guess:
for (var i = 1, len = someN; i < len; i++) {
var $item = $('.item-' + i);
$item.find('.text').css({
'margin-left': -$item.width() / 2,
'margin-bottom': -$item.height() / 2
});
}

Related

Run javascript on multiple selected checkboxes

Hello I am currently writing a web application that calculates a number based on what a user has checked.
You can see it here.
If you go to the link you can see that a person will check a checkbox first and enter a value from the dropdown and type 2 values to get an output.
What I need help with is being able to calculate the value for more than one checkbox at a time.
Right now I can only calculate the value for a checkbox one at a time even if multiple are selected. So basically I need help try to figure how to calculate for more than one checkbox at a time.
I was using an if statement inside my javascript file but thats not giving me the result that I want.
Just remove else if statements, change for IF only. But I have to say that's solution its not that scalable, and for a big application could turns into a nightmare.
I recommend you try to use $("input:checked").each(function() {}); if you dont want to store it and just show the values on the client to avoid further problems and bad code. With your line of thought, you'll need everytime make copy and paste those IF's everytime you want to implement new form labels.
$(document).ready(function(){
function check(){
if($('#checkbox1').is(':checked')){
var pokemonCount = parseInt($("#pokecount1").val());
var candyCount = parseInt($("#candycount1").val());
var reqCandy = parseInt($("#dropdown1 :selected").val());
var evolveAmount = 0;
evolveAmount = Math.floor(((candyCount + pokemonCount) - 1) / (reqCandy));
$("#p1").html(evolveAmount);
}
if($('#checkbox2').is(':checked')){
var pokemonCount2 = parseInt($("#pokecount2").val());
var candyCount2 = parseInt($("#candycount2").val());
var reqCandy2 = parseInt($("#dropdown2 :selected").val());
var evolveAmount2 = 0;
evolveAmount2 = Math.floor(((candyCount2 + pokemonCount2) - 1) / (reqCandy2));
$("#p2").html(evolveAmount2);
}
if ($('#checkbox3').is(':checked')){
var pokemonCount3 = parseInt($("#pokecount3").val());
var candyCount3 = parseInt($("#candycount3").val());
var reqCandy3 = parseInt($("#dropdown3 :selected").val());
var evolveAmount3 = 0;
evolveAmount3 = Math.floor(((candyCount3 + pokemonCount3) - 1) / (reqCandy3));
$("#p3").html(evolveAmount3);
}
}
$("#compute").click(function(){
check()
});
});
Just remove Else if to if only
$(document).ready(function(){
function check(){
if($('#checkbox1').is(':checked')){
var pokemonCount = parseInt($("#pokecount1").val());
var candyCount = parseInt($("#candycount1").val());
var reqCandy = parseInt($("#dropdown1 :selected").val());
var evolveAmount = 0;
evolveAmount = Math.floor(((candyCount + pokemonCount) - 1) / (reqCandy));
$("#p1").html(evolveAmount);
}
if($('#checkbox2').is(':checked')){
var pokemonCount2 = parseInt($("#pokecount2").val());
var candyCount2 = parseInt($("#candycount2").val());
var reqCandy2 = parseInt($("#dropdown2 :selected").val());
var evolveAmount2 = 0;
evolveAmount2 = Math.floor(((candyCount2 + pokemonCount2) - 1) / (reqCandy2));
$("#p2").html(evolveAmount2);
}
if ($('#checkbox3').is(':checked')){
var pokemonCount3 = parseInt($("#pokecount3").val());
var candyCount3 = parseInt($("#candycount3").val());
var reqCandy3 = parseInt($("#dropdown3 :selected").val());
var evolveAmount3 = 0;
evolveAmount3 = Math.floor(((candyCount3 + pokemonCount3) - 1) / (reqCandy3));
$("#p3").html(evolveAmount3);
}
}
$("#compute").click(function(){
check()
});
});
You've used elseif, so if the first checkbox is checked then it runs that code and stops. You need a series of if blocks:
if(1.isChecked){
}
if(2.isChecked){
}
You are using else if statements in your code, which means that the code of only one of the 3 if statements can be executed. More info here.
You need to replace them with simple if statements, like this:
$(document).ready(function(){
function check(){
if($('#checkbox1').is(':checked')){
var pokemonCount = parseInt($("#pokecount1").val());
var candyCount = parseInt($("#candycount1").val());
var reqCandy = parseInt($("#dropdown1 :selected").val());
var evolveAmount = 0;
evolveAmount = Math.floor(((candyCount + pokemonCount) - 1) / (reqCandy));
$("#p1").html(evolveAmount);
}
if($('#checkbox2').is(':checked')){
var pokemonCount2 = parseInt($("#pokecount2").val());
var candyCount2 = parseInt($("#candycount2").val());
var reqCandy2 = parseInt($("#dropdown2 :selected").val());
var evolveAmount2 = 0;
evolveAmount2 = Math.floor(((candyCount2 + pokemonCount2) - 1) / (reqCandy2));
$("#p2").html(evolveAmount2);
}
if ($('#checkbox3').is(':checked')){
var pokemonCount3 = parseInt($("#pokecount3").val());
var candyCount3 = parseInt($("#candycount3").val());
var reqCandy3 = parseInt($("#dropdown3 :selected").val());
var evolveAmount3 = 0;
evolveAmount3 = Math.floor(((candyCount3 + pokemonCount3) - 1) / (reqCandy3));
$("#p3").html(evolveAmount3);
}
}
$("#compute").click(function(){
check()
});
});

jQuery .append() after offset

I have this:
<div id="testcase">abcdefghijklmnopqrstuvwxyz</div>
I would like to add this: <span> with an offset.
So when I for example would have the JS function: addSpan(4) this would happen:<div id="testcase">abcd<span>efghijklmnopqrstuvwxyz</div>
To visualise what I'm looking for:
function addSpan(i){
$('#testcase').append('<span>', i);
}
Use slice and concatinate...
function addSpan(i){
var content = $("#testcase").html();
var before = content.slice(0, i);
var after = content.slice(i + 1);
$("#testcase").html(before + "<span></span>" + after);
}
Here another wut i tired LIVE DEMO
$("#btn_clck").on('click', function () {
var gText = $("#testcase").html();
var getlength = gText.length;
var finalValue = "";
for (var i = 0; i < getlength; i++) {
var setData = gText.charAt(i);
if (i == 4) {
finalValue += '<span></span>'
}
finalValue += setData;
}
$("#testcase").text(finalValue);
});
but i think Steini's answers was better

This code doesnt work. trying to use a loop to get the sizes of my images the first one comes but the others dont

$j(document).ready(<script type="text/JavaScript">
function getProps(){
var imgwidth = [];
var imgheight = [];
var w, h;
var width = document.getElementById('des').clientWidth;
var height = document.getElementById('des').clientHeight;
img = document.getElementById('des').getElementsByTagName('img').length;
w = document.getElementById('des').getElementsByTagName('img');
h = document.getElementById('des').getElementsByTagName('img');
for ( count = 0; count < img; count++){
imgwidth[count] = w.item(count).clientWidth;
imgheight[count] = h.item(count).clientHeight;
}
</script>);
I think this is what you want, I refactored your code a little:
function getProps()
{
var imgwidth = [];
var imgheight = [];
var images = document.getElementById('des').getElementsByTagName('img');
var count = images.length;
for ( i = 0; i < count; i++)
{
imgwidth[i] = images[i].clientWidth;
imgheight[i] = images[i].clientHeight;
}
console.log(imgwidth);
console.log(imgheight);
}
$(document).ready(function()
{
getProps()
});​
I have set up a jsfiddle for you to demonstrate this: http://jsfiddle.net/JbpdW/
Edit
If you use jQuery (what you obvilously do), you can simplify that process a little by using:
$("#des img").each(function(i)
{
imgwidth[i] = this.clientWidth;
imgheight[i] = this.clientHeight;
});
with jquery it is very short:
$j(function() {
var result=$j.map($('#des img'),function(el,i) {
var $el=$j(el); //optimize
return {width:$el.width(),height:$el.height()};
});
console.log(result);
});
please note that i used array of objects instead of two variables, it easer to work with one variable than with two :)
http://jsbin.com/uzikeh/2/edit

How to sort a random div order in jQuery?

On page load, I am randomizing the order of the children divs with this Code:
function reorder() {
var grp = $("#team-posts").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$("#team-posts").append($(grp));
}
I cannot seem to figure out how to get the posts back in the original order. Here's the demo of my current code http://jsfiddle.net/JsJs2/
Keep original copy like following before calling reorder() function and use that for reorder later.
var orig = $("#team-posts").children();
$("#undo").click(function() {
orderPosts();
});
function orderPosts() {
$("#team-posts").html( orig ) ;
}
Working demo
Full Code
var orig = $("#team-posts").children(); ///caching original
reorder();
$("#undo").click(function(e) {
e.preventDefault();
orderPosts();
});
function reorder() {
var grp = $("#team-posts").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$("#team-posts").append($(grp));
}
function orderPosts() {
// set original order
$("#team-posts").html(orig);
}
How about an "undo" plugin, assuming it applies?
Just give each item a class with the corresponding order and then get the class name of each div and save it to a variable
$("#team-posts div").each(function() {
var parseIntedClassname = parseInt($(this).attr("class");
arrayName[parseIntedClassname] = $("#team-posts div." + parseIntedClassname).html()
});
You can reorder them from there by saving their html to an array in order
$("#team-posts").html();
for(var i=0;i<arrayName.length;i++){
$("#team-posts").append('<div class="'+i+'">'+arrayName[i]+'</div>');
}
The solution with saving away the original order is probably the best but if you have to dynamically sort it, you can use this:
http://www.w3schools.com/jsref/jsref_sort.asp
function orderPosts() {
var $grp = $("#team-posts"),
ordered = $grp.children().toArray().sort(function(a, b) {
return parseInt($(a).text()) > parseInt($(b).text());
});
$grp.empty().append(ordered);
}

Multiplying Variables Not Alerting

I have a script which calls variable values from input fields and multiplies them,
At the minute my function isnt executing, Im getting no alert neither, I think this is because of my if statement, can anybody see whats going wrong?
function Calculate() {
var ContentMinutes = document.getElementById ("ContentMinutes").value;
var ContentMinutesSelect = document.getElementById('ContentMinutesDD')
.options[document.getElementById('ContentMinutesDD').selectedIndex].value
if (ContentMinutesSelect == 0.0166)
{
var RenderingHours = 10;
var VideoHours = 5;
var VideoSeconds = 1;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
else if (ContentMinutesSelect == 0.0003)
{
var RenderingHours = 1540;
var VideoHours = 54;
var VideoSeconds = 1;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
else
{
var RenderingHours = 6410;
var VideoHours = 345;
var VideoSeconds = 124;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
var NoOfFrames = document.getElementById ("NoOfFrames").value;
//var EstimatedCoreHours = document.getElementById ("EstimatedCoreHours").value;
var ServiceLevel = document.getElementById('SerivceLevelDD')
.options[document.getElementById('SerivceLevelDD').selectedIndex].value;
var RenderHours = 1;
var CoresInTest = document.getElementById ("CoresInTest").value;
var EstimatedCoreHours = GetNumeric(NoOfFrames)
* GetNumeric(RenderingHours)
* GetNumeric(CoresInTest);
var EstimatedTotal = GetNumeric(ServiceLevel)
* GetNumeric(EstimatedCoreHours);
alert('Estimated Cost = '
+EstimatedTotal.toFixed(2)
+ 'Estimated Core Hours = '
+EstimatedCoreHours);
document.getElementById("EstimatedCoreHours").innerHTML =
EstimatedCoreHours.toFixed(2);
document.getElementById("EstimatedTotal").innerHTML =
EstimatedTotal.toFixed(2);
document.getElementById("EstimatedCoreHours").style.backgroundColor="yellow";
document.getElementById("EstimatedTotal").style.backgroundColor="yellow";
}
function GetNumeric(val) {
if (isNaN(parseFloat(val))) {
return 0;
}
return parseFloat(val);
}
if (ContentMinutesSelect == 0.0166) i think when you do .value you will get string result.
So your comparision should be
if (ContentMinutesSelect == "0.0166")
Your code will display no alert if any line before it results in an error , like if there isn't an element with the id 'ContentMinutes' in your document . The best way to debug would be to use something like firebug , or you could always put in a bunch of alerts and figure out what goes wrong.

Categories

Resources