PHP and jQuery Draw numbers animation - php

I've been working on a program to draw cards. I have 54 cards and I want to have them drawn individually. Here's what I've gotten so far. It reads an array, shuffles it, resets it, and then places them with a foreach.
<?
session_start();
include "array.php";
shuffle($cards);
reset($cards);
$i = 1;
foreach($cards as $card){
print <<<HERE
<div id="$i">\n<img src="img/{$card[1]}.gif" alt="{$card[0]}" width="176" height="276"/><br/>
<h1 style="font-family: sans-serif;">{$card[0]}</h1>\n</div><br />\n\n
HERE;
$i++;
}
?>
Each result of each card comes out as this:
<div id="1">
<img src="img/#.gif" alt="Card Name #" width="176" height="276"/><br/>
<h1 style="font-family: sans-serif;">Card Name #</h1>
</div><br />
In array.php, there is a 2-dimensional array which holds the paths and names of each card. For example:
$array = array();
$array[] = array("Card Name 1", "1");
$array[] = array("Card Name 2", "2");
$array[] ...
Anyways, I'm new at jquery and I need help into creating an animation which shows a card and changes the picture for every click in the order which it outputs until it runs out.
How can I create this animation? Do I need to change my code completely to accomplish this? Is there an easier method?
Thanks in advance!

There are lots of ways to do this, but here's the first that came to mind:
$(document).ready(function(){
var i=0,
$cards = $("div").hide();
$cards.click(function(){
$cards.eq(i).slideUp(function() {
i = (i+1)%$cards.length;
$cards.eq(i).slideDown();
});
}).eq(0).slideDown();
});
You should assign your card divs a common class and change the jQuery selector to use it, e.g., $("div.card"), but the general idea is select all the card divs and hide them, show the first, and on click of whichever one is showing hide it and show the next.
I've coded the above to keep looping around, but you can add your own end-of-deck actions as required.
Demo: http://jsfiddle.net/FrrhZ/
jQuery provides a number of animation methods, and you can make the animation as complicated as you like, but for demo purposes I just went with .slideUp() and .slideDown().
By the way, I'd remove the <br> elements from between your individual divs. You don't need them if only one card is displayed at a time, but even to display multiple cards divs are block elements and will display one under then other by default - if you need more spacing set the margins via CSS rather than adding spacer elements.

For your each individual div set opacity 0 and give class="card"
Then use this function
$(document).ready(function()
{
$(".card").animate({opacity:"1"});
});
Ex: http://jsfiddle.net/FrrhZ/10/
The $(".card") is a jQuery selector to get all elements with class ".card". The above will show each card appearing from nowhere, a cool effect.
This is just an example, you can do many more things with jQuery animate(), have a look http://api.jquery.com/animate/
For example, you can set the speed like this
$(".card").animate({opacity:"1"}, 1000);//animation to be completed in 1000 miliseconds.
Or you can show a metro like animation where the entity goes a little up while appearing, to do that add margin-top:10px and opacity:0 to your divs and then use this function
$(document).ready(function anim()
{
$(".card").animate({opacity:"1", marginTop:"0px"}, 'slow');//animate also excepts some keywords for speed like 'slow', 'fast'
});
Ex: http://jsfiddle.net/FrrhZ/14/
You can get even more creative with animate(), these were just few of many things possible with jQuery animate(), you can even chain animations, everything is provided in the link. Go ahead and explore.

Related

How to make drag and drop using dragula js dynamic

I am trying to create a section using dragula js just like this:
http://bevacqua.github.io/dragula/
What I want is, the drag and drop should be dynamic. So that on each drag and drop the position of each element should be saved. How can I do that?
I know it can be done with php and ajax. But no idea on how the position should be manipulated
This question can be broken down into 2 different problems.
How do I keep track of the order of elements?
From what I can tell, dragula does not have a concept of tracking positioning of elements. You will have to devise a way to identify the parent container and the draggable items element. (div in the example). If you need to create the parent containers dynamically, you will need to track their order too. If you have a predefined layout, then all you need to do is track elements order and what parent they belong too. (for example, left or right, if we use the dragula example).
Create an id for each draggable element. You will have something like this.
<div id="left">
<div id="element1">Some text</div>
<div id="element2">Some other text</div>
</div>
When an element is dropped you will need to capture the element that was dropped and it's order to the parent container. To do this, you can use the jQuery index function to find the new index relative to the parent container. You will then need to reorder the list as you have it saved on the server side.
draggableElements.on('drop',function(el)
{
var parentElId = $(el).parent().attr('id');
var droppedElIndex = $(el).index();
var droppedElId = $(el).attr('id');
$.ajax({
url: "itemDropped.php",
type: 'GET',
data: { parentIdParam: parentElId,
droppedIndexParam: droppedElIndex,
droppedIdParam: droppedElId }
}).done(function() {
//do something else
});
});
How do I save the ordering of the elements?
This depends on your requirements. If you are saving the heirarchy to a database you will need to save the parent container ID for each element, the order or position it is in and the elements ID.
To rerender the page with the elements in the same order they were dropped in you would simply loop over all the elements in each container and render them in the order they are saved.
Review this [http://codepen.io/rachelslurs/pen/EjKmLG]
Also other example mostly similar with your dragula js example
sample code for to check and customize

Is there a simple way using CSS or Javascript to change the background color of a div based on the value of a field

What I'm attempting to do is have the background of a div change from white to a very light green based on the results of a value returned from MySQL. So I have a form that has a field called payment status, if they are paid in full I want the background color of the div to change to light green. If payment displays no payment I want the background to display a very light red.
I did a search and attempted using this change background color based on value
but it's a bit too complicated for me. I was hoping I could do this with javascript or css or a combination.
This is my line of code for the payment status <td>Payment : </td>
<td style="height: 30px; width: 145px;"><?php echo $data2['pay_status']?></td>
so based on the value of pay_status is what I want to use to change the background color.
*******UPDATE********
So after a lot of trial and error I've come up with this jsfiddle
This works like a charm if I needed to change the background color of an input box but I need to change the div background color? can someone help me modify this to change the div instead of the input box?
I figured it out using javascript here is the jsfiddle
Thanks to everybody that gave suggestions!
var div = document.getElementById('info');
var payment = document.getElementById('paystatus');
var green = "#66ff99";
var red = "#ff9999";
if (payment.value == 'Paid in Full') {
div.style.backgroundColor = green;
} else {
div.style.backgroundColor = red;
}
Assuming you have a PHP bool variable paidInFull, it should be straightforward to transfer that to a color on the page. For example:
<?php
$paidinFull = $mysqlresult['paymentStatus'] == 'paidinfull';
?>
<div style='background-color: <?php echo $paidInFull ? "#aaaaff" : "#ffaaaa"; ?>'>
Payment status
</div>
Set a php variable to be what is returned from fronts database and have that as the class of the containing element. You'll need a couple of classes in your CSS.
Using phone and hard to write code on it but you can either use php to echo to value into the class value of the parent HTML element or run an if else and display the div depending on outcome
...
Forgot {} in the above buy this will work
I think I know what you're looking for. here is a jsfiddle with everything working. It's all javascript. Basically, based on the response from your server, you just highlight it green if it's paid and leave it white otherwise. Here's the javascript snippet:
// call this function after you've gotten your answer from your server
$('.payment').each(function () {
//first you see what's inside the div
var wordsInsideDiv = $(this).html();
if(wordsInsideDiv.indexOf('not') != -1) {
$(this).css('background-color', 'white');
}
else{
$(this).css('background-color', 'green');
}
});
and the html I used:
the guy hasn't paid
<div class="payment">
paid status: not paid
</div>
the guy paid
<div class="payment">
paid status: totally paid
</div>
Notice that i'm simply using the word "not" to trigger whether or not I highlight it green. So whatever the actual value of your response from the database shoudl determine your if statement in the javascript.
cheers!

Change form position on page load

Ok, I know this can be done, for I've seen it before. Yet I have no idea how to make it work I have searched everywhere for an answer.
What I need is for my form to randomly change positions when the page loads from 3 different spots on the page. So for example....
[Here] [Here] [Here]
Could all be possible spots the form could load in but only in 1 spot for each time it loads. I don't know what information you need to help me. I will just give my form for now.
<form name="inputt" action="" method="post">
<div align="center">
<input type="submit" class="catch" value="Catch Pokemon" name="catch">
</div>
</form>
If you need more just ask.
Just my inital thought, but you could write CSS for the 3 different position class, and call them things like 'position1', 'position2','position3'. Then on page load in javascript (or in PHP) if you want, generate a random number between 1 and 3, add the class "position"+randomNumber to the element, and then it will be in one of those places. This is similar to a technique I used for random background images.
Update
Also, if you want to use more descriptive class names for the locations, you could keep a mapping of a number to a class name (or use something like position in an array), to relate a a random number to the class to apply.
Code
CSS:
<style>
.position1 {
// Whatever style you want for position 1
}
.position2 {
// Whatever style you want for position 2
}
.position3 {
// Whatever style you want for position 3
}
</style>
JS:
$(document).ready( function () {
var randomIndex = Math.floor(Math.random()*3)+1; //3 is the number of options you have; +1 makes the range 1 - 3 instead of 0 - 2
$('#my-form').addClass('position'+randomIndex); //Adds the new class the element with id = 'my-form'
}
If you mean by "load" a page refresh than you will have to persist the previous location of the form either in cookie or some other mechanism. Based on the last location of the form you can decide which location should be next.
If the form is being reloaded based on ajax calls, then I would advise using a var to store the previous location of the form and make the next location not be the same as previous by checking the value of the var. If each time form loads position should be unique than use an array to store previously used display locations.
HTH.

best approach for jQuery slider with dynamic prev/next content?

Here's a somewhat complex puzzle, I'd love some feedback on how others would approach this.
This site is basically a free regional news blog. The image at the bottom demonstrates the layout (ignore the date overlap glitch). It's coded in PHP, jQuery and xajax.
My question has to do with dynamic content loading. As is, on page-load, I assign the arrows to the URL of the prev/next articles. No prob. The URLs are friendly, the page reloads to the next article, and I can cycle through them all day long.
But ... I'd like to turn the arrows into a slider (not an href) with the following behavior:
Clicking the right arrow will ...
Begin loading the new content offscreen via xajax,
Cause the old content to slide left (from onscreen to offscreen)
flush with the new content also sliding left (from offscreen to
onscreen).
Why? Sliders are awesome, and I think it would look pro. And this is basic slider stuff (like this jQuery scrollLeft slider) except with content being dynamically loaded on click of the arrow, which raises some questions:
What's the best approach for this?
Do I use PHP to pre-populate ALL empty hidden article DIVs?
Do I use jQuery to append/prepend/remove article DIVs with each arrow click?
What would the jQuery "scrollLeft" offset look like? The content DIV is static width, but would I be better off with jQuery scrollTo?
I hope my question is clear ... Any suggestions would be most appreciated!
Here's the solution I came up with.
http://jsfiddle.net/tXUwZ/
If anyone has ideas on how to clean it up or make it tighter, please let me know!
Many thanks to #Jamie for the push in the right direction!
You have two options in my opinion:
Populate each slider on page load so that a jQuery click function animates the content
Populating the data on a per slide basis using an AJAX call
If it's only a few items/slides, then I'd populate on page load. If you're looking at lots of slides (which you might expect with a daily news blog) or if each slide will contain a lot of data (such as high-res images, etc.) I'd go with the second option.
The second option is easy to do. All you'd need is three divs (one for the onscreen slide and two for the flanking offscreen slides that will 'replace' the onscreen one when either arrow is clicked). I'd use something like this:
<div class="container">
<div class="inner-container">
<div class="back"></div>
<div class="content off_screen_left" id="1"></div>
<div class="content on_screen" id="2"></div>
<div class="content off_screen_right" id="3"></div>
<div class="next"></div>
</div>
</div>
And the required CSS:
.container{width:200px;height:150px;overflow:hidden}
.inner-container{width:600px;height:150px;margin-left:-200px}
.content{float:left;width:200px;height:150px}
And as for jQuery:
$(".next").live('click', function(){
var current_id=$(this).prev(".on_screen").attr("id"); // get current page ID
$(".content").css("float","right"); // float all elements to the right
$(".off_screen_right").animate({display:none;}); // make the furthest right disappear gradually
$(".on_screen").attr("class","off_screen_right"); // make on_screen the new off_screen_right and add the correct ID attribute
$(".off_screen_left").attr("class","content on_screen"); // make off_screen_left the new on_screen
$(".container").prepend('<div class="content off_screen_left" id="'+current_id-1+'"></div>'); // add the new off_screen_left element and add the correct ID attribute
$(".off_screen_left").load("load-content.php?page_id="+current_id-1); // populate the new off_screen_left element
});
$(".back").live('click', function(){
var current_id=$(this).next(".on_screen").attr("id"); // get current page ID
$(".content").css("float","left"); // float all elements to the left
$(".off_screen_left").animate({display:none;}); // make the furthest left disappear gradually
$(".on_screen").attr("class","off_screen_left"); // make on_screen the new off_screen_left and add the correct ID attribute
$(".off_screen_right").attr("class","content on_screen"); // make off_screen_right the new on_screen
$(".container").append('<div class="content off_screen_right" id="'+current_id+1+'"></div>'); // add the new off_screen_left element and add the correct ID attribute
$(".off_screen_right").load("load-content.php?page_id="+current_id+1); // populate the new off_screen_left element
});
But that's just one option. You can use a slider out of the box but I prefer to custom code things so that I know exactly what I'm doing.

Handling jQuery click events on divs produced in a foreach loop

I have an HTML div:
<div id='text_icon_<?php $i++; ?>' class="text_icon">Some Text</div>
that I print inside a foreach loop. I am using ajax to handle the click() event on it and change its text to Done!, so I have an output like:
<div class="text">Done!</div>
If I run the loop 4 times and I click on one of the divs (i.e. the one with class text_icon) then only first one is working while the rest of the divs are not working.
Update:
Your update indicates the below is not the problem, the IDs are unique.
Without your jQuery code it's hard to help you debug, so here's an example of how it can be done:
HTML:
<div id='text_icon1' class='text_icon'>Div #1</div>
<div id='text_icon2' class='text_icon'>Div #2</div>
<div id='text_icon3' class='text_icon'>Div #3</div>
<div id='text_icon4' class='text_icon'>Div #4</div>
JavaScript code using jQuery:
$("div.text_icon").click(function() {
// Within the `click` handler, `this` points to the
// DOM element. If you're kicking off some ajax something,
// you'll probably be doing something like this:
// Grab `this` to a variable we can access from the
// `success` closure
var theDiv = this;
// Do our call
$.ajax({
url: "your_url_here",
success: function() {
// It worked, udate the div
$(theDiv).text("Done!");
}
});
});
Live copy
Original answer:
If you're really using "DIV id='text_icon' class="text_icon..../DIV", e.g.:
<DIV id='text_icon' class="text_icon">....</DIV>
...then the problem is that the id is not unique. ID values must be unique on the page (reference). That would seem to fit with the symptom you describe, with "only the first one" working. Most browsers, when given invalid HTML with multiple IDs, will use the ID on the first element in document order and ignore the remaining ones.
If you don't need the div to have an ID at all, you can just remove it. Otherwise, just ensure the ID is unique, e.g.:
<DIV id='text_icon1' class="text_icon">....</DIV>
<DIV id='text_icon2' class="text_icon">....</DIV>
<DIV id='text_icon3' class="text_icon">....</DIV>
<DIV id='text_icon4' class="text_icon">....</DIV>
As far as I can tell, you are giving your divs the same ID. Targetting multiple elements with the same ID is impossible, the IDs need to be unique.
Try this:
$i = 1;
foreach ($array as $al) {
echo "<div id='text_icon_$i'>blablabla</div>";
$i++;
}
Of course, you'll need to modify your jQuery code too to include a potentially unlimited number of such IDs (I don't know whether performance will be good this way, but I remember doing it once for a comments list on a blog).
Another way would be to use a common class rather than unique IDs :).
Apart from the arguments about unique IDs, could it also be that the click handlers need to be hooked up again after the ajax call? If so, it'd be better to use .live rather than .click.
$("div.text_icon").live("click",
function(event) {
var icon = $(this);
}
}

Categories