Jquery/Javascript Refreshing Click() - javascript

I'm creating a simple game where a player creates a 4 color code by clicking on 6 different colored squares, later on the computer player is suppose to be able to guess what the player has selected but that's to happen much later on. Anyway, the problem I'm running into is with click(). I want it so that when you click on each of the squares the result of which square you click on as well as the order is stored in an array, which is to eventually be the player's 4 color code. So far it looks like the information is being stored but not in the way you would expect. If I click on the orange square for instance, that information is stored 4 times so if I print out the array contents it will look like orange, orange, orange, orange. I want it to reset each time a click happens, if that makes any sense. If I click on blue, purple, orange, green and then print out the array it should say blue, purple, orange, green. Any ideas as to what I'm doing wrong? Thanks!
var colorSelection;
var playerCode = [];
$(document).ready(function() {
$('div.codeOption').mouseenter(function() {
$(this).fadeTo("fast", 0.5);
});
$('div.codeOption').mouseleave(function() {
$(this).fadeTo("fast", 1);
});
});
$('div.codeOption').click(function() {
for (i = 0; i < 4; i++) {
colorSelection = $(this).attr('id');
playerCode[i] = colorSelection;
alert(playerCode);
}
});

Working Fiddle Here
you are looping 4 times and setting the same selection each of those 4 times for every click... You were probably thinking you had to loop through each one and figure out which one was clicked, but your jquery click and subsequent $(this) selector takes care of which one was clicked for you, so no need to loop... try this instead
var colorSelection;
var playerCode = [];
var clickCount = 0;
$(document).ready(function(){
$('div.codeOption').mouseenter(function(){
$(this).fadeTo("fast",0.5);
});
$('div.codeOption').mouseleave(function(){
$(this).fadeTo("fast",1);
});
$('div.codeOption').click(function(){
colorSelection = $(this).attr('id');
playerCode [clickCount] = colorSelection;
alert(playerCode);
clickCount++;
});
});

$('div.codeOption').click(function(){
...
colorSelection = $(this).attr('id');
playerCode [i] = colorSelection;
...
});
you are using $(this) in side div.codeOption which will always point to that particular div which has been clicked. Try using something like .each which will do it for all of the divs. Haven't tested it but hope that helps.
$('div.codeOption').click(function(){
$('div.codeOption').each(function(){
//some code
});
});

Related

Switching between divs like pages

I have several div elements with incremental IDs (e.g. div0, div1, div2 (I know this is bad practice - I'm developing a dynamic CSV-to-HTML converter for Outlook calendar exports)) and I'd like to switch between them using jQuery linked to forward/back buttons . What I'm trying to do is as follows (in meaningless pseudo-code):
int pos = 0
forward.onclick
hide ("#div"+pos)
pos++
show ("#div"+pos)
back.onclick
if pos != 0
hide ("#div"+pos)
pos--
show ("#div"+pos)
Since I know next to nothing about jQuery, my questions are 1. What would the syntax be for implementing the above example (assuming I'm on the right track), and 2. Is there a way in jQuery to somehow check for an upper boundary so the counter doesn't increase above the number of divs?
If you want to know how many divs you have in jQuery, select them and take the length of your selection:
$('.div').length
You could even just use that selection to cycle through which divs to show:
var $divs = $('.div');
var upperLimit = $divs.length - 1;
var index = 0;
// on arrow click
$($divs[index]).hide();
index++ (or index--, depending on the arrow)
$($divs[index]).show();
int is not a data type in JavaScript. Use var. Declaration would be var pos = Number(0). To prevent exceeding the boundaries of number of divs, declare a variable with the number of divs you have, and inside your hide and show calls, use pos℅divLength instead of pos. Suppose you have total divs as 4, you will never exceed div3 this way. It will iterate from div0 to div3. Refer this to learn how to use show and hide methods.
Here's a demo.
var index = 0;
$('#div' + index).show();
$('#next').click(function () {
index++;
$('#back').prop('disabled', false);
if (index === fakeData.length - 1) {
$('#next').prop('disabled', true);
}
$('.items').hide();
$('#div' + index).show();
});
$('#back').click(function () {
index--;
$('#next').prop('disabled', false);
if (index === 0) {
$('#back').prop('disabled', true);
}
$('.items').hide();
$('#div' + index).show();
});
The above code will disable and enable the next and back buttons based on whether you are at the beginning or the end of your list of data. It hides all elements and then shows the specific one that should be shown.

change rows depending on the ordernumber in database

I'm creating for my education-project a pizza-ordering website. With the help of the stackoverflow-community I've achieved already a lot - so thank you! But now I'm stuck and can't find any working solution to my problem.
Question
How can I change the row color alternating (white / grey / white / grey ...) depending on the ordernumber in the database(mysqli)? The ordernumber can be in more than one row, so I can not simple change the color row by row.
I've tried with jquery, but this works only if the ordering numbers remain always in the list (even/odd) ... if an order is cancelled, then it doesn't works anymore (see image with missing ordernumber 7)
Here is the code in jquery:
$(document).ready(function() {
var check = 0;
for(var i =0; i<= $("tr").length;i++){
$("tr").each(function(){
if(parseInt($(this).find("#bestnr").text())==check){
if(check%2 == 0){
$(this).css("background-color","white");
}else{
$(this).css("background-color","#DCDCDC");
}
}
});
check +=1;
}
});
Any ideas? Thanks for your help!
Since you're working with JQuery, something like this ought to do the trick - explanations in code comments.
$(document).ready(function() {
// define the initial "previous order id" as 0 assuming
// there will never be an order with id 0
var previousOrderId = 0;
var previousBgColour = '#dcdcdc';
var thisBgColour;
// loop the table rows
$("tr").each(function() {
// determine "this" row id (assuming bestnr is short for bestelnummer)
// and that the text in that table cell *is* the order number
// I've changed this to a class as an id HAS to be unique
// you'll need to update your code to accommodate
var thisOrderId = parseInt($(this).find(".bestnr").text());
// define the background colour based on whether the order id has changed
// if it has change it
if(thisOrderId != previousOrderId) {
thisBgColour = previousBgColour == '#dcdcdc' ? '#ffffff' : '#dcdcdc';
previousBgColour = thisBgColour;
}
else {
thisBgColour = previousBgColour;
}
$(this).css({'background-color' : thisBgColour});
//update the previousOrderId to this id
previousOrderId = thisOrderId;
});
});
You're basically storing the previous order id and comparing it to the current order id - if the order id hasn't changed it'll use the previous background colour, if it has it'll flipflop it to the alternate colour.
If it is just alternating colors, you can use CSS directly and not worry about anything else:
tr:nth-child(odd) {
background-color:white;
}
tr:nth-child(even) {
background-color:#DCDCDC;
}
If this is somehow dependent on logic from the backend, we can look at adding a class in jQuery and adding colors to this class via CSS

Javascript setInterval() creates a weird outcome(?)

I encountered a weird problem with the setInterval method that I really don't get.
So I created a website with 25 boxes and the idea was that clicking on any box would change the backgroundColor of that box for half a second after which it would return to the original color. After that animation finished the next box would change its color for half a second and then go back to the original state. This cycle would continue until it reached the last box.
The code I wrote for that is this:
window.onload = function() {
var box = document.getElementsByClassName("box");
for (i = 0; i < box.length; i++) {
box[i].onclick = starter;
}
}
function starter(eo) {
var box = eo.target;
var counter = eo.target.id;
box.style.backgroundColor = "#1A237E";
setTimeout(cont, 500, counter);
}
function cont(counter) {
var box = document.getElementsByClassName("box");
box[counter].style.backgroundColor = "white";
counter++;
box[counter].style.backgroundColor = "#1A237E";
if (counter < box.length) {
setInterval(cont, 500, counter);
}
}
(All the boxes have the class "box" and are labelled with IDs from 0 to 24)
The code actually executes and is technically working. The weird thing is that after about 8 iterations several boxes start to flash up simultaneously(different boxes for each iteration of the cont() function) and the whole code slows down enormously. This happens regardless of the starting position.
I have no idea where I made a mistake in the code, can someone explain to me white it happens?
Many thanks in advance :)

Changing row color on click - ASP.NET and JavaScript

Using the e.Row.Attributes.Add("onclick", "this.style.backgroundColor='yellow'"); I am able to highlight a selection with a mouseclick in an ASP.NET GridView.
This works, however, each row that is clicked has it's background colour changed, and if I click on another row, the previously clicked row remains highlighted.
Is there any way on how to fix this, i.e. reset all other rows and highlight only currently selected?
Lets assume it will looks like
then
e.Row.Attributes.Add("class", "colorchange");
and your javascript code will looks like
$('.colorchange').click(function()
{
$('.colorchange').backgroundColor="";
$(this).backgroundColor="your color name";
});
If you set AutoGenerateSelectButton property to true then its possible.
Add class clicked and toggle it on click event:
No JQuery:
Server side:
e.Row.Attributes.Add("onclick", "Click(this)");
Client side:
Click = function(el) {
var clicked = document.querySelectorAll(".clicked");
for (var i = 0, length = clicked.length; i < length; i++) {
removeClass(clicked[i], "clicked");
}
el.className = el.className + "clicked";
}
http://jsfiddle.net/Cd2Q9/11/
JQuery:
Server side:
e.Row.Attributes.Add("class", "clickable");
Client side:
$(".clickable").click(function() {
$(".clicked").removeClass("clicked");
$(this).addClass("clicked");
});
http://jsfiddle.net/aB5cm/

Add new item to bottom of scrollabe div

I'm trying to append a div to the bottom of a another div, by clicking a button in javascript, but once the height of the outer container is reached, it no longer scrolls the list to the bottom, after an insert.
Please see the fiddle here
If you click the red add button until you get to about 13 items in the list, it seems something goes wrong with the scrollTop function, and it it no longer functions correctly (hovers around the same spot in).
I'm pretty lost on this, and have tried a bunch of different combinations of css settings for both the container and side div. Please help me.
I've reformatted your code to be more jQuery-esque. The main change, however, was to change the list.scrollTop() function so that it just scrolls to the bottom of list:
$(document).ready(function() {
var list = $("#q-d-list");
$(document).on('click', '#add', function() {
$('.active', list).removeClass("active");
var count = list.children().length + 1;
var active = $('<div />', {
'data-qid': count,
'class': 'mli active'
}).text('q' + count).appendTo(list);
list.scrollTop(list[0].scrollHeight);
});
});​
Demo: http://jsfiddle.net/MrvcB/19/
Use
list.scrollTop(list.get(0).scrollHeight);
rather than
list.scrollTop($(".active").offset().top);
Try:
$(document).ready(function () {
var count = 2;
$("#add").live("click", function () {
var list= $("#q-d-list");
// remove the active class from the old item
var $clone = $(list.find("div:last-child").removeClass("active").clone());
count+=1;
var str_count = "q"+count.toString();
$clone.addClass("active").attr("data-qid",str_count).text(str_count);
list.append($clone);
list.scrollTop(list.get(0).scrollHeight);
});
});
http://jsfiddle.net/H4Kb3/

Categories

Resources