Select 2 random divs with the same class jQuery - javascript

my question is simple, suppose I have 10 divs:
<div class="someDiv"></div>
<div class="someDiv"></div>
<div class="someDiv"></div>
<div class="someDiv"></div>
<div class="someDiv"></div>
<div class="someDiv"></div>
<div class="someDiv"></div>
<div class="someDiv"></div>
<div class="someDiv"></div>
<div class="someDiv"></div>
And I want that when I click 'foo' just 2 of the divs change their background to red. How can I achieve this with something like Math.random from js?

Try this - Use Math.Random and parseInt
Working Demo Here
$(document).ready(function(){
var r1 = (Math.random()*10);
var r2 = (Math.random()*10);
if(parseInt(r1)==parseInt(r2)) // IF BOTH ARE SAME
{
if(parseInt(r1)==10)
{
r2=r2-1;
}
else
{
r2=r2+1;
}
}
var allDiv = $('.someDiv');
$(allDiv[parseInt(r1)]).css({'background':'red'});
$(allDiv[parseInt(r2)]).css({'background':'red'});
});

Here is the simplified version of https://stackoverflow.com/a/11186765/2000051
Demo: http://jsfiddle.net/lotusgodkk/fK8Xw/69/
JS:
function shuffle(array) {
var m = array.length,
t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
$(function () {
$("button").click(function () {
var $all = $(".someDiv").removeClass("red");
$(shuffle($all).slice(0, 3)).addClass("red");
});
});

A generalized approach for specified number of elements to change.
just change var numOfDivToChange=2; to apply the effect to more elements.
$(document).ready(function(){
var numOfDivToChange=2;
$('.foo').click(function(){
//get all similar elements array
var allFoos = document.getElementsByClassName('someDiv');
//sanity check
if(numOfDivToChange>allFoos)
return false;
for(var i=0;i<numOfDivToChange;i++)
{
//generate a random index
var randIndex = Math.floor((Math.random() * allFoos.length) + 1);
//set the css changes you want
allFoos[randIndex].css('background','red');
}
});
});

Try This
UPDATE:
$(document).ready(function(){
$('.foo').click(function(){
var rand1 = Math.floor((Math.random() * 10) + 1);
var rand2 = Math.floor((Math.random() * 10) + 1);
var a = document.getElementsByClassName('someDiv')[rand1];
var b = document.getElementsByClassName('someDiv')[rand2];
a.css('background','red');
b.css('background','red');
});
});

Related

Percentage with Jquery and write in multiples divs

I am learning JS and I have a question about a specific situation. I am trying to calculate % and write in the div #porc using JS. My question is how to make this function better and how to work with multiple divs with same class.
The HTML
<div class="wrapper">
<div class="precoCheio">400,00</div>
<div class="precoDesc">150,00</div>
<div id="porc"></div>
</div>
<div class="wrapper">
<div class="precoCheio">200,00</div>
<div class="precoDesc">150,00</div>
<div id="porc"></div>
</div>
<div class="wrapper">
<div class="precoCheio">1000,00</div>
<div class="precoDesc">600,00</div>
<div id="porc"></div>
</div>
The JS
function calculaPorcentagem(){
var precoCheio = $(".wrapper .precoCheio").text();
var precoDesc = $(".precoDesc").text();
precoCheio = precoCheio.replace(".", "");
precoCheio = precoCheio.replace(",", ".");
precoDesc = precoDesc.replace(".", "");
precoDesc = precoDesc.replace(",", ".");
precoDesc = precoDesc.replace(".", "");
precoDesc = precoDesc.replace(",", ".");
var porcentagem = precoDesc * 100 / precoCheio / 100;
var porcentagem = porcentagem.toFixed(0) - 100;
$('#porc').html(porcentagem + ' % OFF ');
var val = $("#porc").html();
$("#porc").html(val.substring(1, val.length));
};
Try this:
// run on document ready
$(function() {
// cycle through each wrapper
$('.wrapper').each(function() {
var wrapper = $(this), // get current wrapper
cheio = wrapper.children('.precoCheio'), // get child 'precoCheio' of current wrapper
cheioVal = parseFloat(cheio.text().replace(/\./g, "").replace(",", ".")), // replace ALL dots then change first comma to dot
desc = wrapper.children('.precoDesc'), // get child 'precoDesc' of current wrapper
descVal = parseFloat(desc.text().replace(/\./g, "").replace(",", ".")),
porc = wrapper.children('.porc'); // get child 'porc' of current wrapper
// do your calculation
var porcentagem = 100 - ((descVal / cheioVal) * 100);
// put result into current porc
porc.html(porcentagem + ' % OFF');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="precoCheio">400,00</div>
<div class="precoDesc">150,00</div>
<div class="porc"></div>
</div><br />
<div class="wrapper">
<div class="precoCheio">200,00</div>
<div class="precoDesc">150,00</div>
<div class="porc"></div>
</div><br />
<div class="wrapper">
<div class="precoCheio">1000,00</div>
<div class="precoDesc">600,00</div>
<div class="porc"></div>
</div>
In addition
$.fn.html can accept functions too. Like this
function calculaPorcentagem(){
var $wrapper = $(this).parrent();
var precoCheio = $wrapper.find(".precoCheio").text();
var precoDesc = $wrapper.find(".precoDesc").text();
//here some your logic
precoCheio = precoCheio.replace(".", "");
precoCheio = precoCheio.replace(",", ".");
precoDesc = precoDesc.replace(".", "");
precoDesc = precoDesc.replace(",", ".");
precoDesc = precoDesc.replace(".", "");
precoDesc = precoDesc.replace(",", ".");
var porcentagem = precoDesc * 100 / precoCheio / 100;
var porcentagem = porcentagem.toFixed(0) - 100;
return porcentagem + ' % OFF';
};
$('.porc').html(calculaPorcentagem);

document.getElementById wont give me "style" to change background color

So I have a function that "rolls" a dice, and I'm using netbeans to code my program, so when I write "document.getElementById." i dont get the "style" option, rather the only "s" is "seal".... I tried ignoring that and writing it either way, still didn't work, here's my code:
<script>
function roll()
{
var firstDie = document.getElementById("dice1");
var secondDie = document.getElementById("dice2");
firstDie.innerHTML = Math.floor(Math.random() * 7);
secondDie.innerHTML = Math.floor(Math.random() * 7);
if (firstDie>secondDie)
{
document.getElementById("dice1").style.backgroundColor = "green";
}
}
</script>
</head>
<body>
<div class="game">
<div id="dice1" class="dice">0</div>
<div id="dice2" class="dice">0</div>
<div id="feed" class="feed">
<br><br>
<button onclick="roll()" id="rollButton" class="rollButton">Roll</button>
</div>
</div>
It's just not entering the if statement because domElement > otherElement would be false.
document.createElement('div') > document.createElement('div') //false
What you want is:
var firstDieValue = Math.floor(Math.random() * 7),
secondDieValue = Math.floor(Math.random() * 7);
firstDie.innerHTML = firstDieValue;
secondDie.innerHTML = secondDieValue;
if (firstDieValue > secondDieValue) { ... }
Also, consider extracting your dice rolling strategy e.g.:
var diceRoll = randomDiceRoll(2),
firstDieValue = diceRoll[0],
secondDieValue = diceRoll[1];
function randomDiceRoll(diceCount) {
return Array.apply(0, Array(diceCount)).map(function () {
return Math.floor(Math.random() * 7);
});
}
It's because you are not parsing to integer the content of div value :
var a = Math.floor(Math.random() * 7);
var b = Math.floor(Math.random() * 7);
firstDie.innerHTML = a;
secondDie.innerHTML = b;
if (a>b)
{
document.getElementById("dice1").style.backgroundColor = "green";
}
}
http://jsfiddle.net/bnspfg7p/5/

Unable to slice strings retrieved from div's

I'm having trouble slicing text I retrieved from a div with javascript/jquery. I thought you could slice every string and that the .text() function always returned a string so I fail to see the problem. Any help will be greatly appreciated!
Fiddle
Html:
<body>
<div class="vaknaam">Div 1 :<span class="totaal">55%</span>
</div>
<div class="vaknaam">Div 2 :<span class="totaal">60%</span>
</div>
<div class="vaknaam">Div 3 :<span class="totaal">64%</span>
</div>
<div class="vaknaam">Div 4 :<span class="totaal">76%</span>
</div>
<div class="vaknaam">Div 5 :<span class="totaal">63%</span>
</div>
</body>
Javascript:
$(function () {
var divs = {};
var tempString, vakken = {};
$('.vaknaam').each(function (key, value) {
tempString = $(value).contents().filter(function () {
return this.nodeType == 3;
}).text();
tempString = tempString.slice(0, - 2);
vakken[tempString] = $(value).children('span').text();
});
for (var property in vakken) {
$('body').append("<p>" + property + "</p>");
}
});
You have several errors.
You need to declare an initialise the var vakken.
The slice method does not modify the string so you should assign what returns to something.
property var is just an index so you need to ask for vakken[property]
Your code should look like this:
$(function () {
var divs = {};
var tempString, vakken = {}; //1
$('.vaknaam').each(function (key, value) {
tempString = $(value).contents().filter(function () {
return this.nodeType == 3;
}).text();
tempString = tempString.slice(0, -4); //2
vakken[tempString] = $(value).children('span').text();
});
for (var property in vakken) {
$('body').append("<p>" + property + "</p>"); //3
}
});
Check out this codepen.
slice doesn't modify the initial string, which is immutable. Try:
tempString = tempString.slice(0, - 2);

JS for each replacement of manual copy function

I am looking for way to automate this selection.
For example, I will have 10 double inputs (20 inputs total) and I don't want to write JS script for each inputs, but simply use each() function (I am open to different ways) and declare only selectors.
JsFiddle: http://jsfiddle.net/vs7fa/
Idea:
var SELECTORS_H = array();
$.each(SELECTORS_H){
$('SELECTOR_H').keyup(function () {
// do magic
$('SELECTOR_V').val(num);
});
$('SELECTOR_V').keyup(function () {
// do magic
$('SELECTOR_H').val(num);
});
}
HTML:
<label for="h_one">H_ONE:</label>
<input type="text" name="h_one">
<label for="v_one">V_ONE:</label>
<input type="text" name="v_one">
There will be more of inputs. Pattern is:
h_one, v_one
h_two, v_two
h_something, v_something
...
JS:
$(function() {
$('input[name="h_one"]').keyup(function() {
var one = $(this).val();
if (one > 0) {
var num = Math.abs(one) * -1;
}
else {
var num = Math.abs(one) * 1;
}
$('input[name="v_one"]').val(num);
});
$('input[name="v_one"]').keyup(function() {
var two = $(this).val();
if (two > 0) {
var num = Math.abs(two) * -1;
}
else {
var num = Math.abs(two) * 1;
}
$('input[name="h_one"]').val(num);
});
});
You can handle this using a selector with a common class for all your element and data-attributes to know the element and the linked elements.
HTML:
<label>H_ONE:</label>
<input type="text" class="handler" data-id="h1" data-link="v1" />
<br>
<label>V_ONE:</label>
<input type="text" class="handler" data-id="v1" data-link="h1" />
Code:
$(function () {
$('.handler').keyup(function () {
var one = $(this).val();
if (one > 0) {
var num = Math.abs(one) * -1;
} else {
var num = Math.abs(one) * 1;
}
$('input[data-id=' + $(this).attr("data-link")+']').val(num);
});
});
Demo: http://jsfiddle.net/8KgTk/
may be this...
Jsfiddle: http://jsfiddle.net/vs7fa/3/
$('input[name="h_one"]').keyup(function () {
var num = DoMagic($(this));
$('input[name="v_one"]').val(num);
});
$('input[name="v_one"]').keyup(function () {
var num = DoMagic($(this));
$('input[name="h_one"]').val(num);
});
function DoMagic(element) {
var one = $(element).val();
if (one > 0) {
var num = Math.abs(one) * -1;
} else {
var num = Math.abs(one) * 1;
}
return num;
}
You should be able to perform the .each function by using jQuery and making the items the same class.
such as:
<label class="forElement" for="h_one">H_ONE:</label>
<input class="inputElement" type="text" name="h_one">
<label class="forElement"for="v_one">V_ONE:</label>
<input class="inputElement" type="text" name="v_one">
$('.forElement').each( function() {
//some code
}
You can do this without adding extra attributes if you want.
$(function () {
$('input[name^="h_"], input[name^="v_"]').keyup(function () {
var one = $(this).val();
var num = - one;
var inputType = $(this).attr("name").substr(0,1);
var inputNumber = $(this).attr("name").substr(2);
$('input[name="'+(inputType == 'v' ? 'h' : 'v')+'_' + inputNumber + '"]').val(num);
});
});
However Irvin Dominin aka Edward's solution is quite good.
Here's a sollution that doesn't require extra markup, and doesn't use string concatenation for logic. It uses $.proxy() to get correct scoping.
Fiddle

update total with multiple list items by clicking on images

So I'm not entirely sure what I'm missing, but I can't seem to get the total price to add properly. I can get each individual price, though.
Basically the idea is to click on a grayed out image, it generates a list(working) and it's suppose to give a price(which is does) and if you click on another image it should update the price, which would add to the previous price.
Can someone please tell me what I'm missing or doing wrong?
Here is my fiddle: http://jsfiddle.net/lolsen7/Acnx4/2/
HTML:
<div id="station-builder">
<a class="tools4" href="#"> <img id="keyboard" class="part" src="http://placehold.it/100x100" alt="Keyboard"/><span class="info">apple keyboard</span></a>
<a class="tools5" href="#"><img id="mouse2" class="part" src="http://placehold.it/100x100" alt="Mouse" ><span class="info">apple mouse</span></a
</div>
<div id="summaryTotal">
<p>Get this system for as little as:</p>
</div>
<ul id="list">
<li>2201L elo Touchscreen monitor</li>
<li>Mac mini</li>
</ul>
Javascript:
$ //JS FOR HARDWARE SECTION
$(document).ready(function () {
$(".part").mouseover(function () {
if (this.className !== 'part selected') {
$(this).attr('src', 'http://placehold.it/100x100' + this.id + 'http://placehold.it/100x100');
}
$(this).mouseout(function () {
if (this.className !== 'part selected') {
$(this).attr('src', 'http://placehold.it/100x100' + this.id + 'http://placehold.it/100x100');
}
});
});
var list = document.getElementById("list");
var summaryTotal = document.getElementById("summaryTotal");
var sum = 0;
var total = 0;
var finalTotal = 0;
$(".part").click(function () {
if (this.className == 'part') {
$(this).attr('src', 'http://placehold.it/100x100' + this.id + 'http://placehold.it/100x100');
console.log(this);
if (this.id == 'keyboard') {
var li = document.createElement("li");
//li.setAttribute("alt","keyboard_li");
li.setAttribute("id", "keyboard_li");
li.appendChild(document.createTextNode('Keyboard'));
list.appendChild(li);
var keyboardPrice = "59";
sum = keyboardPrice * 1.2;
console.log(sum);
total = sum / 40;
console.log(total);
var span = document.createElement('span');
span.setAttribute('id', 'keyboardTotal');
summaryTotal.appendChild(span);
$('#keyboardTotal').append(total);
}
if (this.id == 'mouse2') {
li = document.createElement("li");
li.setAttribute("id", "mouse_li");
li.appendChild(document.createTextNode('Mouse'));
list.appendChild(li);
var mousePrice = "59";
sum = mousePrice * 1.2;
console.log(sum);
total = sum / 40;
console.log(total);
var span = document.createElement('span');
span.setAttribute('id', 'mouseTotal');
summaryTotal.appendChild(span);
$('#mouseTotal').append(total);
}
} else {
$(this).attr('src', 'http://placehold.it/100x100' + this.id + 'http://placehold.it/100x100');
console.log(this);
if (this.id == "keyboard") {
$("#keyboard_li").remove();
$('#keyboardTotal').remove();
}
if (this.id == "mouse2") {
$("#mouse_li").remove();
}
}
$(this).toggleClass('selected');
});
total = $('#keyboardTotal') + $('#mouseTotal');
});
Can you make the following changes?
var kbtotal = 0;//added
var mstotal = 0;//added
var keyboardPrice = 59;
sum = keyboardPrice * 1.2;
console.log(sum);
kbtotal = sum / 40; // changed
console.log(kbtotal); // changed
var mousePrice = 59;
sum = mousePrice * 1.2;
console.log(sum);
mstotal = sum / 40; // changed
console.log(mstotal); // changed
var finaltotal = parseFloat(kbtotal) + parseFloat(mstotal);
$('#finaltotal').text(finaltotal); // added
<div id="summaryTotal">
<p>Get this system for as little as: <div id="finaltotal"></div></p>
</div>

Categories

Resources