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
Related
I have this image for a slider. I want it to fade to the next image after the button is clicked. The JQuery makes the image fade in and out to make the transition cleaner when the src changes. However, the image stays the same after fading.
Html
<button onclick = "prev()" id = "prev">Prev</button>
<img id = "slider" src = "" height = "600px" width = "600px"/>
<button onclick = "next()" id = "next">Next</button>
JQuery
var images = ['', '', ''];
var num = 0;
function next() {
var slider = $('#slider');
num++;
if(num >= images.length) {
num = 0;
}
slider.fadeOut('slow', function() {
slider.src = images[num];
slider.fadeIn('slow');
});
}
function prev() {
var slider = $('#slider');
num--;
if(num < 0) {
num = images.length-1;
}
slider.fadeOut('slow', function() {
slider.src = images[num];
slider.fadeIn('slow');
});
}
I have taken out the images I tested it with as their links were too long. The three slider images would be in the JQuery "images" variable and the starting one in the image src.
Assuming that images is an array of image URLs, then your mistake is trying to set slider.src instead of slider.attr('src, value);.
So, use this instead:
slider.attr('src', images[num]);
I want to select or deselect a div with a click.
I want this :
click 1 = add color and select div
click 2 = if is the same id go pink, if different go white.
My problem is when I click on the first div (go red), then the second div (first go white and second too), then the third div, the third div go pink, or I want re run the script (for make the third div red like the first div).
My code:
$(document).ready(function () {
$i = 1;
$firstcase = "";
$(".blackcase").click(function firstclick(event) {
if ($i == 1)
{
$("#" + event.target.id).css("background-color", "red");
$firstvalue = $("\#" + event.target.id).html();
$firstcase = "\#" + event.target.id + "";
$i++;
}
else
{
return false;
}
$(".blackcase").one("click", function (event) {
$firstcase2 = "\#" + event.target.id + "";
if ($("#" + event.target.id).is($firstcase))
{
$("#" + event.target.id).css("background-color", "pink");
$i = 0;
$firstcase = "";
return;
}
else
{
$(".blackcase").css("background-color", "white");
$i = 1;
$firstcase = "";
return false;
}
});
return false;
});
});
JSFIDDLE: https://jsfiddle.net/12gwq95u/3/
You can massively simplify your logic if you have a single event handler and store the last clicked id in a variable outside of the click handler. Try this:
var lastClicked = '';
$(".blackcase").click(function(e) {
e.preventDefault();
$('.blackcase').removeClass('red pink');
$(this).addClass(lastClicked != this.id ? 'red' : 'pink');
lastClicked = this.id;
});
Example fiddle
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/
I am writing this in JavaScript, and the issue is that I can't seem to figure out how to make a permutation. Ideally, I want to click the button and image would change to next, from a1.jpg to a2.jpg to a3.jpg to a4.jpg to a1.jpg and so on... But when I wrote this code, it would skip a2 and a3. I also did rearrange the conditionals since I realized that it reads from the top to bottom, but it would always skip one of the four pictures.
function changeImage() {
if (document.images) {
if (document["buttonOne"].src == a3.src){
document["buttonOne"].src = a4.src}
}
if (document.images) {
if (document["buttonOne"].src == a2.src){
document["buttonOne"].src = a3.src
}
if (document.images) {
if (document["buttonOne"].src == a1.src){
document["buttonOne"].src = a2.src}
}
if (document.images) {
if (document["buttonOne"].src == a4.src){
document["buttonOne"].src = a1.src}
}
}
Try it in a more simple way
var imgs = ['a1.jpg', 'a2.jpg', 'a3.jpg', 'a4.jpg'];
function changeImage() {
var img = document["buttonOne"];
if (!img._index) img._index = 0;
img.src = imgs[img._index++];
if (img._index >= imgs.length) img._index = 0;
}
img._index replaces the global variable with index of the shown image. Good to use when you want to change a few images, each of them will keep its own counter.
ps: if the only thing that changes is the number in the filename then the code can be even shorter without an array:
function changeImage(max) {
var img = document["buttonOne"];
if (!img._index) img._index = 0;
img.src = 'a' + img._index + '.jpg';
if (img._index >= max) img._index = 0;
}
I have a literal array of image IDs and I need to swap them in <img src=""> to Next or Previous image on buttons click events. The initial current image ID is known from the img src provided server-side on initial page load.
Obviously, before swapping, the URL needs to be constructed with the target ID like this:
'http://site.com/images/' + imageID + '.jpg'
I'm a JS/jQuery beginner and would like to learn a correct, minimalistic approach. TIA.
My code to start off:
var images=["777777","666666","555555"];
var max = $(images).length;
$('#swapnextimg').click{
$("#imageswap").attr('src', ...... );
}
<a id="swapnextimg"></a>
<a id="swapprevsimg"></a>
<div id="imagebox">
<img id="imageswap" src="http://site.com/images/123456.jpg">
</div>
Here is an example:
http://jsfiddle.net/ndFGL/
$(function() {
// Image ID array
var images = ['240', '260', '250', '123', '200'];
var max = images.length;
// Get current image src
var curSrc = $('#imageswap').attr('src');
// Find ID in image src
var curID = curSrc.replace(/.*\/(.*?)\.jpg/i, '$1');
var curIdx = 0;
// Search image list for index of current ID
while (curIdx < max) {
if (images[curIdx] == curID) {
break;
}
curIdx++;
}
// For convenience
var imgSrcBase = 'http://placehold.it/';
// Next image on button (and image) click
$('#swapnextimg,#imageswap').click( function() {
curIdx = (curIdx+1) % max;
$("#imageswap").attr('src', imgSrcBase+images[curIdx]+'.jpg');
});
// Prev image on button click
$('#swapprevsimg').click( function() {
curIdx = (curIdx+max-1) % max;
$("#imageswap").attr('src', imgSrcBase+images[curIdx]+'.jpg');
});
});
Try below code,
var images=["777777","666666","555555"];
var max = $(images).length;
var imgPtr = 0;
$('#swapnextimg').click{
if (imgPtr == max) {
//comment the below return and set imgPtr to 0 for rotating the images
return;
}
$("#imageswap").attr('src', 'http://site.com/images/' + images[imgPtr++] + '.jpg');
}
$('#swapprevsimg').click{
if (imgPtr == 0) {
//comment the below return and set imgPtr to max-1 for rotating the images
return;
}
$("#imageswap").attr('src', 'http://site.com/images/' + images[imgPtr--] + '.jpg');
}
<a id="swapnextimg"></a>
<a id="swapprevsimg"></a>
<div id="imagebox">
<img id="imageswap" src="http://site.com/images/123456.jpg">
</div>
I assume that you've got one img tag, and only one. And that the purpose of this is to change that single image tag.
To do that you will need the nex and prev button.
<div id="container">
<img src="#" data-num="" />
<span class"prev">prev</span>
<span class"next">next</span>
</div>
The object:
var obj = [0: 'dog', 1: 'cat'];
now for the next and prev to work. We are going to take a look at the .on() method.
$('.container span').on('click', function(){
var $this = $(this), // span
currentNum = $this.siblings('img').data('num'), // img data-num
nextNum = $this.is('.next') ? currentNum+1 : currentNum-1, // if class is next add 1, if not remove 1
link = "http://site.com/images/" + obj[nextNum] + ".jpg" // the link
// either it's not the last images or it returns
nextNum != obj.length() || return
$('img').attr('src', link).data('num', nextNum)
})
Hope this helped you. If not please let me know