How to make random selector only pick shown items? - javascript

Yeah not very familiar with JQuery and I'm trying to make a random lunch picker for our web team.
http://jsfiddle.net/vy8RL/1/
I want to hide certain items. For example when you hit the "Quick Eats" button it only displays 4 options and when you hit "EAT ME" it still selects the LI's that are hidden. Is there any way to allow it only to select options that are visible?
$(document).ready(function() {
$("#button").click(function(){
random();
});
$("#unhealthy-food").click(function(){
$(".unhealthy").hide();
});
$("#all").click(function(){
$("li").show();
});
$("#fast-food").click(function(){
$(".food").hide();
$(".fast").show();
});
});
function random() {
$("li.selected").removeClass("selected");
var menuItems = $("ul#list li");
var numItems = menuItems.length;
if(window.sessionStorage && window.sessionStorage.getItem("selected")) {
previous = Number(window.sessionStorage.getItem("selected"));
} else {
previous = -1;
}
var selected = Math.floor(Math.random()*numItems);
while(selected === previous && numItems > 1) {
selected = Math.floor(Math.random()*numItems);
}
if(window.sessionStorage) window.sessionStorage.setItem("selected", selected);
$("ul#list li:nth-child("+(selected+1)+")").addClass("selected");
}

You can use the :visible selector:
function random() {
$("li.selected").removeClass("selected");
var menuItems = $("#list li").filter(':visible');
var numItems = menuItems.length;
// ...
menuItems.eq(selected).addClass("selected");
}
Please note that I have replaced the $("ul#list li:nth-child("+(selected+1)+")") with the cached collection + eq() method.
http://jsfiddle.net/3n9ex/

here you go. I just added tracking of menu preference. Also added $(".food").show(); in line 9 to correct a bug.
$(document).ready(function() {
var user_choice = ".food";
$("#button").click(function(){
random(user_choice);
});
$("#unhealthy-food").click(function(){
user_choice = "li:not(.unhealthy)";
$(".food").show();
$(".unhealthy").hide();
});
$("#all").click(function(){
$("li").show();
user_choice = ".food";
});
$("#fast-food").click(function(){
$(".food").hide();
$(".fast").show();
user_choice = ".fast";
});
});
function random(user_choice) {
$("li.selected").removeClass("selected");
var menuItems = $(user_choice);
console.log(menuItems);
var numItems = menuItems.length;
if(window.sessionStorage && window.sessionStorage.getItem("selected")) {
previous = Number(window.sessionStorage.getItem("selected"));
} else {
previous = -1;
}
var selected = Math.floor(Math.random()*numItems);
while(selected === previous && numItems > 1) {
selected = Math.floor(Math.random()*numItems);
}
if(window.sessionStorage) window.sessionStorage.setItem("selected", selected);
$(menuItems[selected]).addClass("selected");
}
http://jsfiddle.net/vy8RL/19/

Related

Index not being counted on click

I have a slider where I want to keep track of the current position of the slider. The function that runs when the ('next') and ('prev') are being clicked, is supposed to log the current position of the slider.
Unfortunately it skips the first child and starts the count on the second item in the slider. Instead of the first item being index 0, the second item is index 0
$(document).foundation()
$('.bullet').first().addClass('active');
//sets first item to active
$('.slider-item').first().addClass('active');
function dec() {
var $this = $(this);
var current = $('.slider-items').find('.active');
var position = $('.slider-items').children().index(current);
console.log(position)
}
$('.next, .prev').click(function() {
dec();
var $this = $(this);
var current = $('.slider-items').find('.active');
var position = $('.slider-items').children().index(current);
var numItems = $('.slider-item').length;
if ($this.hasClass('next')) {
if (position < numItems - 1) {
$('.active').removeClass('active').next().addClass('active');
} else {
$('.slider-item').removeClass('active').first().addClass('active');
$('.bullet').removeClass('active').first().addClass('active');
} //else
} else {
if (position === 0) {
$('.slider-item').removeClass('active').last().addClass('active');
$('.bullet').removeClass('active').last().addClass('active');
} else {
$('.active').removeClass('active').prev().addClass('active');
}
}
}); // click function
The code seems to work when I run it against a simple bullet list example. It correctly states that the first bullet point is index 0. Are you simply calling the dec() function in the wrong place? Note that when you click next, you are logging the current position before the change is made to the position. I updated the dec() code to accept a parameter to show what I mean.
$(document).ready(function() {
//sets first item to active
$('.slider-item').first().addClass('active');
function dec(prefix) {
var $this = $(this);
var current = $('.slider-items').find('.active');
var position = $('.slider-items').children().index(current);
console.log(prefix + position);
}
$('.next, .prev').click(function() {
dec("before click handled: ");
var $this = $(this);
var current = $('.slider-items').find('.active');
var position = $('.slider-items').children().index(current);
var numItems = $('.slider-item').length;
if ($this.hasClass('next')) {
if (position < numItems - 1) {
$('.active').removeClass('active').next().addClass('active');
} else {
$('.slider-item').removeClass('active').first().addClass('active');
$('.bullet').removeClass('active').first().addClass('active');
} //else
} else {
if (position === 0) {
$('.slider-item').removeClass('active').last().addClass('active');
$('.bullet').removeClass('active').last().addClass('active');
} else {
$('.active').removeClass('active').prev().addClass('active');
}
}
dec("after click handled: ");
})}); // click function
li.active {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="slider-items">
<li class="slider-item">A</li>
<li class="slider-item">B</li>
<li class="slider-item">C</li>
<li class="slider-item">D</li>
</ul>
<button class="prev">Prev</button>
<button class="next">Next</button>

Change background color with checkbox, limited number of checkboxes selectable

Desired: User can only click on 2 out of 3 displayed checkboxes; when the user clicks on a checkbox, the checkbox background turns orange.
Currently: The first checkbox selected acts as desired. The second checkbox ticks, but does not change background color. Upon clicking again, it un-ticks and changes to the desired background color (yet it is not selected). A 3rd checkbox is not selectable whilst two are already selected.
Requesting: Help to achieve the desired, thank you!
Fiddle: http://jsfiddle.net/0fkn1xs4/
Code:
$('input.playerCheckbox').on('change', function(event) {
var selectableFriends = 2;
if($('.playerCheckbox:checked').length > selectableFriends) {
this.checked = false;
}
numberCurrentlySelected = $('.playerCheckbox:checked').length;
if(numberCurrentlySelected < selectableFriends) {
$(this).closest("li").toggleClass("checked");
}
});
$('input.playerCheckbox').on('change', function(event) {
var selectableFriends = 2;
if($('.playerCheckbox:checked').length > selectableFriends) {
this.checked = false;
}
$(this).closest("li").toggleClass("checked", this.checked);
});
A slightly cleaner implementation that does what you want. Check out the JSFiddle
Try this:
$('input.playerCheckbox').on('change', function (event) {
var selectableFriends = 2;
if ($('.playerCheckbox:checked').length > selectableFriends) {
this.checked = false;
} else {
$(this).closest("li").toggleClass("checked");
}
numberCurrentlySelected = $('.playerCheckbox:checked').length;
});
Check it out here: JSFIDDLE
$('input.playerCheckbox').on('change', function(event) {
var selectableFriends = 2;
var numberCurrentlySelected = $('.playerCheckbox:checked').length;
if(numberCurrentlySelected > selectableFriends) {
this.checked = false;
}
if(numberCurrentlySelected <= selectableFriends) {
$(this).closest("li").toggleClass("checked");
}
});
I just changed the second part to <= rather than < and then created the numberCurrentlySelected variable earlier on so that you aren't calling querying more than once. Caeths is better though instead of using a second if statement it just uses an else, makes sense and gets rid of a comparison.
DEMO
$('input.playerCheckbox').on('change', function(event) {
var selectableFriends = 2;
numberCurrentlySelected = $('.playerCheckbox:checked').length;
if(numberCurrentlySelected <= selectableFriends) {
$(this).closest("li").toggleClass("checked");
}
if($('.playerCheckbox:checked').length > selectableFriends) {
this.checked = false;
$(this).closest("li").removeClass('checked');
}
});
This works in Fiddler for ya.
$('.playerCheckbox').change(function() {
if($('.playerCheckbox:checked').length > 2) {this.checked = false; }
else{
if( this.checked == true ) {$(this).closest("li").addClass("checked");}
if( this.checked == false ) {$(this).closest("li").removeClass("checked");}
}
});

limit javascript toggle according to select box value

Here is link of my current fiddle
jsFiddle
JS --
$('.click').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'http://imageshack.us/a/img703/8236/l6hu.png') src = 'http://imageshack.us/a/img20/1651/fibz.png';
if (origsrc == 'http://imageshack.us/a/img20/1651/fibz.png') src = 'http://imageshack.us/a/img703/8236/l6hu.png';
$(this).attr('src', src);
}
});
i am able to toggle image onclick with another image and vice versa. This is okay, but i want to limit the toggle only when green image is already selected. If i select 3 from select box then i can toggle white image into green image only 3 times, not more than 3. I also need help for another scenerio - if i select 3 from select box and toggle first 3 image and next moment i change the 2nd image into white and click 5th image to turn green then it will be possible. I am week in javascript or jquery, so need proper information about this problem. So plz help me out.
Here is a more comprehensive approach fiddle which will keep your limit in sync and handle discrepancies when the limit changes.
var quantity = 0; // will maintain limit
var stack = []; // will maintain ordered green buttons
$("#select").change(runWrapper);
function runWrapper() {
quantity = Number($("#select").val()); // set the limit
groom(); // turn off those that were turned on last
//run(); // this is your run function, uncomment
}
function groom(){
// let's test if we are over the limit
while(stack.length > quantity) {
// remove last which was set to green
$(stack.pop()).trigger("click")
// to remove the oldest/first set to green use
// $(stack.shift()).trigger("click")
}
}
$('.click').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'http://imageshack.us/a/img703/8236/l6hu.png') {
// limit reached
if(stack.length >= quantity) {
alert(quantity + " limit reached!");
return;
}
src = 'http://imageshack.us/a/img20/1651/fibz.png';
// turning green push the DOM reference to the top of the stack
stack.push(this);
}
if (origsrc == 'http://imageshack.us/a/img20/1651/fibz.png') {
src = 'http://imageshack.us/a/img703/8236/l6hu.png';
// turning white remove the DOM reference from stack
var self = this;
stack = $.grep(stack, function(val) {
return self != val;
})
console.warn(stack);
}
$(this).attr('src', src);
}
});
You can update the function like this - fiddle is here - http://jsfiddle.net/4QkM8/5/
I changed id of select box to selQty
var selectedCount = 0;
$('.click').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'http://imageshack.us/a/img703/8236/l6hu.png'){ if (selectedCount < $('#selQty').val()){src = 'http://imageshack.us/a/img20/1651/fibz.png';
selectedCount ++;
} }
if (origsrc == 'http://imageshack.us/a/img20/1651/fibz.png') {src = 'http://imageshack.us/a/img703/8236/l6hu.png';selectedCount --;}
$(this).attr('src', src == '' ? origsrc : src);
}
});
use a variable to keep track of how many items have been selected, and compare it to the quantity in the select box.
var count = 0;
var unselected_img = 'http://imageshack.us/a/img703/8236/l6hu.png';
var selected_img = 'http://imageshack.us/a/img20/1651/fibz.png';
$('.click').on({
'click': function () {
var max_allowed = parseInt($("#select").val(), 10);
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == unselected_img && count < max_allowed) {
src = selected_img;
count++;
} else if (origsrc == selected_img) {
src = unselected_img;
count--;
} else {
alert("Too many selected.");
}
if (src) {
$(this).attr('src', src);
}
}
});
DEMO

FadeIn multiples of 6 divs at a time with click

I have this code below that basically gets a number of elements and stops them at 6 items. I have then got a button that when clicked loads in remaining divs.
I just want it to load in 6 divs at a time. Does anyone know the way forward to do this at all?
Here is the javascript:
function click_load() {
var count = 0;
var item = $('.newsmainimages');
//var itemClick = $('Load More');
$(item).each(function() {
if (++count == 6) {
$(this).parent().append('<div class="nextClick">Load More</div>');
}
else if (count > 6) {
$(this).css('display','none');
}
});
$('.nextClick a').click(function() {
$(item).each(function(item) {
$(this).delay(200*item).fadeIn("slow");
});
alert(item);
return false;
});
}
Cheers
You can use slice for this kind of things
DEMO
$(function(){
var count = 6;
showListItems(0 , count);
$('button').click(function() {
showListItems(0, ($('ul li:visible').length) + count);
});
function showListItems(firstNumber, lastNumber)
{
$('ul li').slice(firstNumber, lastNumber).fadeIn("slow");
}
});​

jquery - filtering of html elements on page issue

I have created a javascript filter that is working but not all the time. To first see this in action, visit the following link. On the left side, click on the Bridgestone e6 link under "Brand Model". It returns nothing, but in reality it should return 3 products in the view.
The way the filter works is as follows. I grab the value of the item clicked on the sidebar, then I search the html elements in the main view to see if there are any matches. If there are, I only show those products in the view and hide the rest.
The javascript that takes care of this is (also you can see it here):
Is it some whitespace issue or something incorrect in my JS? I tried to use the jQuery trim function to no avail.
The javascript:
var noProductMatches = jQuery('.no-products-found');
jQuery('#filter-by-brand li a').click(function()
{
noProductMatches.hide();
var brandNameSelected = jQuery(this).html();
var productVendorFromCollection = jQuery("#product-vendor");
var productContainer = jQuery('#product-collection .productBoxWrapper');
if (brandNameSelected == 'All Brands' )
{
productContainer.fadeIn("slow");
}
else
{
var results = jQuery(".productBoxWrapper")
.fadeOut(100)
.delay(100)
.filter(function()
{
return jQuery(this).html().indexOf(brandNameSelected) > -1 || jQuery(this).html().indexOf(productVendorFromCollection) > -1;
})
.each(function(index, item)
{
jQuery(item).fadeIn("slow");
});
if (results.length == 0)
{
noProductMatches.fadeIn();
}
}
});
jQuery('#filter-by-model li a').click(function()
{
noProductMatches.hide();
var brandNameSelected = jQuery.trim(jQuery(this).html());
var productContainer = jQuery('#product-collection .productBoxWrapper');
if (brandNameSelected == 'Any Model' )
{
productContainer.fadeIn("slow");
}
else
{
var results = productContainer
.fadeOut(100)
.delay(100)
.filter(function()
{
return jQuery.trim(jQuery(this).html()).indexOf(brandNameSelected) > -1;
})
.each(function(index, item)
{
jQuery(item).fadeIn("slow");
});
if (results.length == 0)
{
noProductMatches.fadeIn();
}
}
});
jQuery('#filter-by-price li a').click(function()
{
noProductMatches.hide();
var priceRangeSelectedItem = jQuery(this).html();
var minSelectedPrice = parseInt( jQuery(this).attr("name") );
var maxSelectedPrice = parseInt( jQuery(this).attr("title") );
var productContainer = jQuery('#product-collection .productBoxWrapper');
if (priceRangeSelectedItem == 'Any Price')
{
productContainer.fadeIn("slow");
}
else
{
var results = jQuery(".productBoxWrapper")
.fadeOut(100)
.delay(100)
.filter(function()
{
var minProductPrice = parseInt( jQuery(this).find("#lowestPriceRange").html() );
var maxProductPrice = parseInt( jQuery(this).find("#highestPriceRange").html() );
//alert(minProductPrice);
//alert(maxProductPrice);
return (minProductPrice >= minSelectedPrice && maxProductPrice <= maxSelectedPrice);
})
.each(function(index, item)
{
jQuery(item).fadeIn("slow");
});
if (results.length == 0)
{
noProductMatches.fadeIn();
}
}
});
The problem is that it is mixed case. In the menu it says Bridgestone e6 but on the page it says Bridgestone E6, with an uppercase E. Either you have to make everything lowercase when you search our make sure they are equal in the menu and on the page.

Categories