How to get random element in jquery? - javascript

How can I return a random element in jQuery by doing something like $(.class).random.click()?
So, if .class had 10 links, it would randomly click one of them.
Here is what I did:
var rand_num = Math.floor(Math.random()*$('.member_name_and_thumb_list a').size());
$(".member_name_and_thumb_list a").eq(rand_num).click();

You can write a custom filter (taken from here):
jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"], {
random: function(a, i, m, r) {
if (i == 0) {
jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
};
return i == jQuery.jQueryRandom;
}
});
Example usage:
$('.class:random').click()
The same thing but as a plugin instead:
​jQuery.fn.random = function() {
var randomIndex = Math.floor(Math.random() * this.length);
return jQuery(this[randomIndex]);
};
Example usage:
$('.class').random().click()

If you don't want to hard code the number of elements to choose from, this works:
things = $('.class');
$(things[Math.floor(Math.random()*things.length)]).click()

var n_elements = $(".someClass").length;
var random = Math.floor(Math.random()*n_elements);
$(".someClass").eq(random).click();

var rand = Math.floor(Math.random()*10);
$('.class').eq(rand).click();
Math.random() gets you a pseudo-random number between 0 and 1, so multiplying it by 10 and rounding it down gets you 0 to 9. .eq() is 0 indexed, so this will get you a random jQuery element out of the 10 you have.

I'd suggest doing it the jQuery way using .eq() and .trigger().
$elements.eq(Math.floor(Math.random() * $elements.length)).trigger('click');

You can select random item by class name using jquery method eq()
see the example bellow.
var len = $(".class").length
var random = Math.floor( Math.random() * len ) + 1;
$(".class").eq(random).click();

randojs.com makes this a simple one-liner:
rando($("a")).value[0].click()
The ".value" is there because you also have the option to get the index of the random jQuery element. The "[0]" is there to turn the jQuery element into a plain JavaScript element. If you add the following to the head of your html document, you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.
<script src="https://randojs.com/1.0.0.js"></script>

Related

How to make this javascript, show random post by it's label?

I have searching about random post and it's show Math.random() function, but because my lack of knowledge about javascripting so I need your help to make this javascript work on random, thanks.
<script type='text/javascript'>
//<![CDATA[[
function CompletedProject(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
var judulPost = json.feed.entry[i].title.$t;
var thumbPost = json.feed.entry[i].media$thumbnail.url;
//var linkPost = json.feed.entry[i].link[1].href;
var linkPost;
// Get rel=alternate for truly post url
for (var j=0; j < json.feed.entry[i].link.length; j++)
{
if (json.feed.entry[i].link[j].rel == 'alternate')
{
linkPost = json.feed.entry[i].link[j].href;
break;
}
}
var showcompleted = '<div class="ani-item"><img alt="'+judulPost+'" class="shine" data-original="'+thumbPost+'"/><h4>'+judulPost+'</h4></div>';
document.write(showcompleted);
}
}
//]]>
</script>
<script src='/feeds/posts/default/-/Complete?alt=json-in-script&callback=CompletedProject'/>
var randomNumber = Math.floor(Math.random() * yourlabels.length);
yourlabels[randomNumber].yourmethod;
That's one way to use Math.random() to generate random integers for use as indexes. Here is a link to a project where I randomly generate a quote and randomly generate a background color with each click of the 'Load Quote' button. Find my Math.random() functions and see if you can incorporate them.
https://github.com/KyleVassella/P1_RandomQuoteGenerator/blob/gh-pages/js/script.js
Math.floor() is a way to round down to the nearest whole number so that Math.random() can be used to represent an index value.
Note that my project also has that seen property which represents a boolean value and is attached to each one of my quote objects - this is used with a 'while' loop to prevent the same quote or background color from randomly generating more than once until each quote has been shown. You may or may not want this feature.

Squaring each number in an array with dynamically added inputs

I'm trying to calculate the standard deviation of a set of data entered by a user into a form with dynamically added inputs. Thus far I have been able to calculate the sum of the elements in the array, but I cannot figure out how to square each element of the array. I have searched this forum, but trying suggestions from the only applicable result (Square each number in an array in javascript) did not seem to work. Here is a snippet of my code:
$(".calcSD").click(function() {
$("input[type=text]").each(function() {
arr.push($(this).val().trim() || 0);
sum += parseInt($(this).val().trim() || 0);
});
Where .calcSD is the button the user clicks to perform the calculation. Moreover, the length of the array is given by var number = arr.sort().filter(Boolean).length; as the script is intended to filter out any inputs that are left blank.
Also, if it make a difference, inputs are dynamically added to the array via:
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).unbind('click').click(function(e) {
$('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
});
So I ask: how would go about determining the square of each element in the resulting array?
The pow() method returns the value of x to the power of y (x^y)
|| in parseInt will use base as 0 if it returns falsey value
$(".calcSD").click(function() {
var sum = 0;
var arr=[];
$("input[type=text]").each(function() {
var squared = Math.pow(parseInt(this.value)||0, 2);
arr.push(squared);
sum += squared;
});
alert(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text">
<input type="text">
<button class="calcSD">Calculate</button>
I might not have followed you correctly, but couldn't you just multiply the value by itself as it's pushed to the array?
$(".calcSD").click(function() {
$("input[type=text]").each(function() {
arr.push(($(this).val()*$(this).val()).trim() || 0);
sum += parseInt($(this).val().trim() || 0);
});
Ultimately I wanted to be able to sum the squares of the elements in the array (as it is a part of calculating the SD) so I did this and it works:
var sumXsq = 0;
for(var i = 0 ; i <= number ; i++) {
sumXsq += parseInt(arr[i]*arr[i]);
}
but not quite as good as Rayon's answer.

I don't understand how jQuery .each() and .html() methods work

Im Timo. I'm new at web programming and I have this issue. I have made a simple html table with 3 rows. Each td has to have a random numeric value. My problem is that my code puts the same value at every td element.
http://jsfiddle.net/timosergio/30ydu4oe/
Down below is my js code:
$(function() {
randomValues();
//alert(1);
});
var randomValues = function(){
var $td = $('.table').find('td');
// each td has to have a different random value
var random_values = Math.random() * 100 ;
$td.each(function(i){
//console.log(i + ":" + Math.random() * 100);
$td.eq(i).text(random_values);
});
};
This is because you're generating a single random value then using that for each of the tds, rather than generating a new one for each td. So:
$td.each(function(i){
$td.eq(i).text(Math.random(Math.random() * 100));
});
In other words, generate the random value inside the loop, not outside of it.
Furthermore, understand that, inside each callbacks, the context, i.e. this, points to the element being considered. So you don't need
$td.eq(i).text(...
but merely
$(this).text(...
$.each() is essentially a foreach loop. You need to create a new random value on each iteration.
Like this:
var randomValues = function() {
var $td = $('.table').find('td');
// each td has to have a different random value
$td.each(function(i){
//console.log(i + ":" + Math.random() * 100);
var random_value = Math.random() * 100 ;
$td.eq(i).text(random_value);
});
}
It's because your random value is generated before the each statement, so the same value is being used each time.
Move your Math.random()*100 into your .text() and all should work.
The problem has nothing to do with .each() or .html(). You have generated the random value just once and setting the same value to each of the td. You need to do this.
var randomValues = function(){
var $td = $('.table').find('td');
// each td has to have a different random value
// var random_values = Math.random() * 100 ;
$td.each(function(i){
//console.log(i + ":" + Math.random() * 100);
$td.eq(i).text(Math.random() * 100);
});
};

Adding increased count to the DOM for every pass

what I'm hoping to achieve is to increase a count and then append that to the DOM on every pass through using each(). What I have at the moment is the final count added at the end. For example.
Say I have 100 divs, for every pass through it should add the new count as it counts it, like so 1,2,3,4,5,6,7... and so on. But at the moment it counts all the objects and just appends 100 at the end. Please can someone point me in the direction to where I'm going wrong?
I've added a very basic version of what I'm hoping to achieve below... also here is a JSbin (I tried jsfiddle but it seems to be down for me) .
$(".toCount").each(function(i){
$("#count").text(i + 1);
});
$('input').on('click',function () {
var len = $(".toCount").length;
var arr = [];
for (var i = 0; i < len; i++ ) {
arr.push(i+1);
}
$('#count').text(arr.join());
});
I don't know what you mean by 1, 2, 3 ... in case that you want to count the elements step by step you can use setInterval function:
$('input').on('click',function () {
var l = $(".toCount").length,
$c = $('#count'),
i = 0;
var t = setInterval(function() {
i++;
$c.text(i);
if (i === l) clearInterval(t);
}, 10);
});
http://jsbin.com/eronel/17/edit
use append();
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
in your case text() is replacing your div's text so u get 100 at the end ..
$("#count").append(i + 1);
Use append
$("#count").append(i + 1);

Implementing shuffle images function

Im looking for some advice on how to start a shuffle image function, so I have 6 images atm in a div box and I want a function that allows them to shuffle around, how should I start?? Should I put the images in a separate div as well? any help or example code appreciated, thanks
Following is a jQuery solution. You can achieve same results using vanilla JavaScript but it will require few extra lines of code.
<div id="deck">
<div><img src="" /></div>
<div><img src="" /></div>
.
.
.
</div>
// Fisher–Yates Shuffle (Knuth variant)
// To shuffle an array a of n elements (indices 0..n-1):
// for i from n - 1 downto 1 do
// j <- random integer with 0 <= j <= i
// exchange a[j] and a[i]
// jQuery specific:
// 1) remove elements from DOM and convert them into a native JavaScript array
// 2) apply algorithm
// 3) inject the array back to DOM
var a = $("#deck > div").remove().toArray();
for (var i = a.length - 1; i >= 1; i--) {
var j = Math.floor(Math.random() * (i + 1));
var bi = a[i];
var bj = a[j];
a[i] = bj;
a[j] = bi;
}
$("#deck").append(a);
Demo here
I've implemented something like this for a memory card game, so you can probably get some hints from that. Just do a resources search for 'shuffle' in my .js files and you should get an idea how I've done it. From memory, I originally put all my images in a div, then move them around with the shuffle function. I think later on I started shuffling an array of URLs instead then generating the image elements later.
I used Ca-Phun Ung's 'Shuffle' JQuery plugin (although I think I re-wrote my own version to better understand its inner workings). You may find some useful information with that as well. See JQuery Shuffle
Ok, I got this!
var divs = $('selector to get all divs'); // This could be $('img');
function shuffle(divs, iterations) {
var size = divs.size();
for(var i = iterations; i > 0; i--) {
// Pick two divs at random
var div1 = divs[Math.floor(Math.random() * size)],
div2 = divs[Math.floor(Math.random() * size)];
// Ensure they are different divs
if(div1.is(div2)) {
continue;
}
// Swap the two divs
div1.clone().insertAfter(div2);
div2.detach().insertAfter(div1);
div1.detach();
}
};
shuffle(divs, 1000);
Although this will probably be better if you put a divs.hide(), then divs.show() so that you don't see the thrashing. However, maybe that is what you want? May you want a delay in there and use jQuery's animate function to make it fancy. This particular solution requires that the img's position in the DOM determines the location. A more complex solution would be to swap the css position during the loop.
var savedLeft = div1.css("left"),
savedTop = div1.css("top");
div1.css("left", div2.css("left"));
div1.css("top", div2.css("top"));
div2.css("left", savedLeft);
div2.css("top", savedTop);
I haven't actually TRIED this yet, but it looks right from here :P

Categories

Resources