jQuery - placing content within a random div - javascript

I've 252 li's, their IDs defined by numbers between 1 and 252. What I'm trying to achieve is replacing text within a random li every time I click a h1. Yet this doesn't work. What am I missing?
$('h1').click(function() {
var flashNumber = Math.floor((Math.random() * 251) + 1);
$('#'+flashNumber).html('test');
});

The code looks fine. If your HTML is also just a list of <div>s, then I can only see one potential problem - the name of your div#ids. Prior to HTML5 they had to start with a letter. What doctype are you using? Maybe it behaves differently in different browsers?
Try adding a letter to your id names:
$(document).ready(function(){
$('h1').click(function() {
var flashNumber = Math.ceil((Math.random() * 251));
$('#my-divs-' + flashNumber).html('test');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Click</h1>
<div id="my-divs-1"></div>
<div id="my-divs-2"></div>
<div id="my-divs-3"></div>
<div id="my-divs-4"></div>
<div id="my-divs-5"></div>
<div id="my-divs-6"></div>
...
<div id="my-divs-251"></div>

Related

Get Value from another div, subtract, and populate another div with jQuery

I'm trying to get the value of one specific div class, subtract that by 500 and then populate the result into another div.
I'm not quite sure what process I would need in order to populate the result of the subtraction into the other div.
Something like this:
<div class="main-value">5000</div>
<!-- main-value - 500-->
<div class="new-value"></div>
//Script
var main = $(".main-value");
main.html(parseInt(main.html()) - 500 ).appendTo($(".new-value"));
So far, the subtraction work, but I can't get it to append the updated value to the empty div and keep the original one intact.
For that, you need to clone the element otherwise it may update and append the original element. Although parsing the string is optional since the operation is subtraction.
var main = $(".main-value");
main.clone().text(main.text() - 500).appendTo($(".new-value"));
//----^^^^----- clone the element
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-value">5000</div>
<!-- main-value - 500-->
<div class="new-value"></div>
In case you just want to show the result in new-value class then do it like.
var main = $(".main-value");
// update the text content in `new-value` div
$(".new-value").text(main.html() - 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-value">5000</div>
<!-- main-value - 500-->
<div class="new-value"></div>
Try this:
var mainval = $(".main-value").text();
$(".new-value").text(parseInt(mainval) - 500);
Reference: http://api.jquery.com/text/
Break it into two:
var main = $(".main-value");
mainValue = parseInt(main.html());
$(".new-value").html(mainValue);
<!doctype html>
<html>
<body>
<div class="main-value">5000</div>
<div class="new-value"> </div>
<script>
var x= document.getElementsByClassName("main-value")[0].innerHTML;
var y= document.getElementsByClassName("new-value")[0];
y.innerHTML= x-500;
</script>
</body>
</html>

Running a jQuery function on all divs with different values but same class name

What I'm trying to do is run a jQuery function that converts a number score into a bar rating system using the score as a percentage to set the width of the bar. The divs and the scores inside of the divs are being generated dynamically from XML with XSL.
The problem is that the function is taking the score from the first DIV and applying it to all subsequent DIVs instead of taking the score from each DIV separately. For reference, .Product_Rating_Score_Overall is the score, .ratingBar is the grey background behind my score bar, .ratingOverall is the green bar that has its width adjusted to reflect the score percentage. Here is an image of my rating system(as you can see the rating of 2.0 from the first DIV is being transferred to the other DIVs. The ratings for the other DIVs should be as follows 7.0 6.0, 6.0, 6.0 - these are just dummy scores for now):
Here is my html code:
<div id="F26_ResultsDiv" style="display:none">
<div class="items"><div class="ColOne">
<div class="item">
<div class="otherStuff">
<span>Kindermat Basic Red/Blue</span>
<div class="overall"><span><span class="content">
<ul>
<li class="Product_Rating_Score_Overall">2.00</li>
</ul>
</span></span>
<div class="ratingBar">
<div class="ratingOverall">
</div></div></div></div></div>
Here is my jQuery code:
$('.overall').each( function() {
var score = parseFloat($('.Product_Rating_Score_Overall').text()).toFixed(1);
console.log(score);
var scorePerc = score * 10;
$('.ratingOverall').width(scorePerc + '%');
$('.Product_Rating_Score_Overall').text(score);
});
Any help is really appreciated. Thanks so much.
You need to localize your selector:
$('.overall').each( function() {
var score = parseFloat($(this).find('.Product_Rating_Score_Overall').text()).toFixed(1);
console.log(score);
var scorePerc = score * 10;
$(this).find('.ratingOverall').width(scorePerc + '%');
$(this).find('.Product_Rating_Score_Overall').text(score);
});
Update: added fiddle https://jsfiddle.net/mbho2bjj/5/
Using $(this) and find() function.
for each element with class overall you find under it the element with class Product_Rating_Score_Overall
$('.overall').each( function() {
var score = parseFloat($(this).find('.Product_Rating_Score_Overall').text()).toFixed(1);
console.log(score);
var scorePerc = score * 10;
$(this).find('.ratingOverall').width(scorePerc + '%');
$(this).find('.Product_Rating_Score_Overall').text(score);
});
The problem is with your second line and the other references being global and not localized properly. You should be changing it to grab the local value, not the first one each time that appears on the global scope, which is why you are getting the functionality you see now. Right now you think its not working but it is working exactly as it was written. By adjusting the code to act on the local variables inside each '.overall' we will get the proper results that you are looking for.
Try changing that code like this:
$('.overall').each( function() {
var score = parseFloat($(this).find('.Product_Rating_Score_Overall').text()).toFixed(1);
console.log(score);
var scorePerc = score * 10;
$(this).find('.ratingOverall').width(scorePerc + '%');
$(this).find('.Product_Rating_Score_Overall').text(score);
});

Select DIV using its ID + addition

Using a div as selector is easy:
<div id="test1"></div>
$('#test1').doSomething();
I want to target only another div, containing the same ID + _sub:
<div id="test1"></div>
<div id="test1_sub"></div>
$('#test1').find( /* Same ID + "_sub" */ ).doSomething();
How can I do this? I know I can use .attr('id') to take #test1, but I do not how to extend this with _sub.
JS FIDDLE
Of course it would be easy to target the #test1_sub directly, but image I have 1000 divs counting up test1, test2, test3, etc. and want to use this inside of a function.
You do it like this
$('#test1' + "_sub").fadeOut();
Note the quotation-marks containing "_sub".
EDIT: In your answer, you made up an example where you had 100 divs with ids like test1, test2 and so on. Then you could select all elements with an id beginning with test. Like this:
$('*[id^="test"]').fadeOut();
Here you can use start with selector to work with all ids.
jsFiddle
$(document).ready(function(){
$( "*[id^='test1']" ).fadeOut();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="test1">Test 1</div>
<div id="test1_sub"> Test 1 Sub</div>
<div id="test1_asdf">Test 1 ASDF</div>
<div id="test1_sub342"> Test 1 sub342</div>
<div id="test1_sdfsd">Test 1 sdfsd</div>
<div id="test1_45645"> Test 1 45645</div>
Set a variable and chain: (CORRECTED)
var target = $(whatever test div you targetted).attr('id');
$('#'+target + "_sub").doSomething();
You said you were going to use it in a function, so it would be targettable this way for example. Lets say when you click #test1 a function will run on all subs based on the clicked test:
$('.testBoxes').click(function () {
var target = $(this).attr('id');
$('#'+target + "_sub").doSomething();
});

Remove subsequent duplicate elements by class

Via javascript or jquery, I am in need of removing duplicate elements in sets so that one remains. They're all the same, so it doesn't matter which are removed so long as one remains. The page appears as follows:
<div class="column-hr"></div>
<div class="column-hr"></div>
<div class="column-dude"></div>
<div class="column-hr"></div>
<div class="column-hr"></div>
<div class="column-dude"></div>
<div class="column-hr"></div>
One <div class="column-hr"></div> before every <div class="column-dude"></div> needs to stay, but every subsequent hr column before every dude column needs to go.
I tried the following, hoping it would be this simple. Didn't work.
$( "div.column-hr" ).each(function( index ) {
if ($(this).next('div.column.hr')) {
$(this).remove();
}
});
You can achieve this with sibling selector +. Very easy and also the fastest solution, since the browser's CSS engine will be used to select elements:
$(".column-hr + .column-hr").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="column-hr">hr</div>
<div class="column-hr">hr</div>
<div class="column-dude">dude</div>
<div class="column-hr">hr</div>
<div class="column-hr">hr</div>
<div class="column-dude">dude</div>
<div class="column-hr">hr</div>
How it works: CSS selector .column-hr + .column-hr selects .column-hr elements that have immediate previous sibling .column-hr. As the result this expression will select all adjacent .column-hr elements except the very first one, because the first one doesn't have another .column-hr right before it.
You can try this:
$( ".column-hr" ).each(function() {
console.log($(this).html());
console.log($(this).next().attr('class'));
if ($(this).next().attr('class') == 'column-hr') {
$(this).remove();
}
});
https://jsfiddle.net/aodnw5ns/
var classesToRemove = ['column-hr', 'column-dude'];
var $elements;
for (var i = 0, l = classesToRemove.length; i < l; i++) {
// Find elements
$elements = $('.' + classesToRemove[i]);
var elementsLength = $elements.length;
// If there is more than one element
if (elementsLength > 1) {
// get all elements except the first
$elements = $elements.slice(1, elementsLength);
// remove them
$elements.remove();
}
}
// prevent memory leaks
$elements = null;
JSFiddle

Insert a div in a random location in a list of divs

I have a page that looks like so:
<div id="container">
<div class="item">...</div>
<div class="item">...</div>
<div class="item">...</div>
<div class="item">...</div>
</div>
I was wondering if there is a way that I could insert a div randomly between any of the "item" divs, so when the page is loaded, it would look like:
<div id="container">
<div class="item">...</div>
<div class="item">...</div>
<div class="rondomDiv">...</div>
<div class="item">...</div>
<div class="item">...</div>
</div>
All the divs with the "item" class are dynamically generated, and cannot be modified. Any ideas?
Thanks in advance!
Try something like below,
var $items = $('#container').find('.item');
var pos = Math.floor(Math.random() * $items.length)
$('.randomDiv').insertAfter($items.eq(pos));
I'd suggest, pending further information:
$('.item').eq(
/* I'm using the eq() method to select a specific element,
and creating the random number (in the range from 0-(number-of-elements))
within the method to avoid creating unnecessary variables. */
Math.floor(Math.random() * $('.item').length)
/* after() creates an element from the html string, and inserts it after
the element selected earlier with the eq() method */
).after('<div class="random"></div>');
JS Fiddle demo.
A slightly altered, though more verbose, alternative to the above:
$('<div />', {
'class': 'random',
'text': '...'
}).insertAfter($('.item').eq(Math.floor(Math.random() * $('.item').length)));
JS Fiddle demo.
References:
after().
eq().
insertAfter().
Math.floor().
Math.random().
Code:
HTML:
<div id="container">
</div>
JS:
$(document).ready(function(){
for(var i =1; i<10; i++) {
$("#container").append("<div class='item' id='"+i+"'>Item</div>"); /*adding item divs dynamically */
}
/*the real magic is below */
var rand_id = Math.floor((Math.random()*10)+1); /*generating an item divs ID randomly */
$("#"+rand_id).after("<div class='randomDiv'>Random DIv</div>"); /*adding the random div after that div of the rand_id */
});
Fiddle: http://jsfiddle.net/mareebsiddiqui/ULcTc/
Explanation:
This is simple. First I add the item divs dynamically by giving them ID's respectively with starting from 1 and ending on 10. Then I generate a random ID using Math.floor() and Math.random() JavaScript functions. Then I fetch(using a simple technique) the div with that random ID and then after that div I add a random div.
I will not provide code if you tried nothing.
But if you don't know where to start and need a workflow :
Coun't the number of div in container Create a random number between 0 and the number of div.
Append your div after the div with the random number index.
This will work:
function randomDiv() {
var divCount = $(".item").length;
var randomnumber=Math.floor(Math.random()*divCount);
$("div.item:eq(" + randomnumber + ")").after("<div class='randomDiv'>hey im random</div>");
}
Demo: http://jsfiddle.net/meaFv/
This is a case where the non-jQuery answer is equivalent to the jQuery answer, in terms of lines of code:
// Assuming you already have a reference to the random div at "randomDiv"
var container = document.getElementById('container');
var position = Math.floor(Math.random() * container.childNodes.length);
container.insertBefore(randomDiv, childNodes[position]);
Example here: http://jsfiddle.net/qbqfR/ Press RUN a bunch of times to see it in action.
var x=Math.floor(Math.random()*$('#container').children().length);
$('#container div').eq(x).append('<div class="rondomDiv">YAY</div>');
itemLength = $('#container .item').length; //quantity of .items
randomPlace = Math.floor((Math.random()*itemLength)); //some random from 0 to .item length
randomDiv = $('<div />',{
'class':'randomDiv',
text: randomPlace
}); //.randomDiv
$('#container .item').eq(randomPlace).after(randomDiv); //place it after the .item of position 'randomPlace'
http://jsfiddle.net/RaphaelDDL/4tpCy/
Try this -
var $items = $('#container .item');
$items.eq(Math.floor(Math.random() * $items.length ))
.after("<div class='rondomDiv'></div>");

Categories