I have created a while loop that selects random images from from my server and posts it. Now I want to add some jquery code and allow me to click on one of the images and run the slideUp() function in jQuery. Here is my problem. I can click on the first image produced in the while loop but when I click on the second image nothing happens. The slideUp() function does not work. I don't know what to do. Here is the code below.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<?php
$num_dresses = dress_count ();
$i=0;
while ($i < 2){
?>
<style>
div:hover { border:2px solid #021a40; cursor:pointer;}
</style>
<script>
$("div").click(function () {
$(this).slideUp();
});
</script>
<?php
$rand_id = rand(1, $num_dresses);
$dress_feed_data = clothing_data($rand_id, 'file_name', 'user_defined_name', 'user_defined_place' , 'user_who_uploaded', 'match_1');
$new_file_name = $dress_feed_data['file_name'];
if (file_exists('fashion_images/' . $new_file_name)){
echo str_replace("|", " ", $dress_feed_data['user_defined_name']);
?>
<br>
<div>
<img src=" fashion_images/<?php echo $new_file_name;?> " width="50" height="50" />
<div>
<br><br>
<?php
echo str_replace("|", " ", $dress_feed_data['user_defined_place']);
?>
<br><br>
<?php
}
$i++;
}
?>
You are binding the click handler to the elements before the elemnts are inserted into DOM,
Probably when the first call is made no elements called div are there so the binding goes to void, then the first element gets inserted.
Now the binding for second element is made, now it gets attached to first one as it matches $('div') . So you got only forst one working.
The clean way is to take the click binding out of while loop, so that it happens only once, and call it on DOM ready event
<script>
$(document).ready(function(){
$("div").click(function(){
$(this).slideUp();
});
});
</script>
And if you want to make a live binding, which applies to all dynamically added images as well use delegation:
<script>
$(document).ready(function(){
$('body').on('click',"div",function(){
$(this).slideUp();
});
});
</script>
If you are posting the above images with html to a host/parent page, just add the above delegation logic to parent page, and post only the images.
Try this :
<style>
div:hover { margin:10px 0; border:2px solid #021a40; cursor:pointer;}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$("div.randomImage").click(function() {
$(this).slideUp();
});
});
</script>
<?php
$num_dresses = dress_count();
$i=0;
while ($i < 2) {
?>
<?php
$rand_id = rand(1, $num_dresses);
$dress_feed_data = clothing_data($rand_id, 'file_name', 'user_defined_name', 'user_defined_place' , 'user_who_uploaded', 'match_1');
$new_file_name = $dress_feed_data['file_name'];
if (file_exists('fashion_images/' . $new_file_name)) {
echo str_replace("|", " ", $dress_feed_data['user_defined_name']);
?>
<div class="randomImage">
<img src="fashion_images/<?php echo $new_file_name;?>" width="50" height="50" />
</div>
<?php
echo str_replace("|", " ", $dress_feed_data['user_defined_place']);
}
$i++;
}
?>
Notes:
Stylesheet and script moved outside the php while loop. Repetition is unnecessary and undesired.
jQuery statement now inside a $(function(){...}) structure to ensure it runs when the ducument is ready, ie. after the served HTML has been interpreted by the browser to create DOM elements.
class="randomImage" added to the <div>
Second <div> changed to </div>
For readability of source and served page, the PHP and HTML are indented independently.
I've not tried to verify the PHP.
Related
The following piece of code in php, uses a while statement to output variable $the_job_id. For each of the output I want to apply jquery slidetoggle. The problem is that in my code slidetoggle works only for the first output of my while. Not working for the rest. Any idea how i should modify my code in order slidetoggle to work for each of my while outputs?
This is my php code:
<?php
$result = mysql_query("select * from `user_job` where `job_id` IN ($all_saved_job_id) ");
while($run_job = mysql_fetch_array($result)){
$the_job_id = $run_job['job_id'];
echo"<div id='flip'> PRESS TO SLIDE </div>";
echo" <div id='panel'> $the_job_id </div>";
}// end while
?>
this is my script :
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
this is my css :
<style>
#flip{
cursor:pointer;
margin-left:100px;
}
#panel{
padding:0px;
display:none;
}
</style>
id must be unique, otherwise you'll always get the first element in the page with duplicated id, so you need to use class instead:
echo"<div class='flip'> PRESS TO SLIDE </div>";
echo" <div class='panel'> $the_job_id </div>";
then you can use . to target elements by class name:
$(document).ready(function(){
$(".flip").click(function(){
$(this).next().slideToggle("slow");
});
});
Please note that you also need to change your CSS selector using . instead of # accordingly.
I'm using the animated collapse JS library here:
http://www.dynamicdrive.com/dynamicindex17/animatedcollapse.htm
and i'm trying to use it for dynamic div's however it's not toggling. Any ideas?
<head>
<script type="text/javascript" src="includes/js/animatedcollapse.js"></script>
</head>
<body>
<?PHP
for ($i = 1; $i <= 5; $i++) { ?>
<script type="text/javascript">
animatedcollapse.addDiv('location-<?PHP echo $i; ?>', 'fade=1')
</script>
<div id="location-<?PHP echo $i; ?>">
CLOSE
TEST
</div>
TOGGLE
<?PHP } ?>
<script type="text/javascript">
animatedcollapse.ontoggle=function($, divobj, state){}
animatedcollapse.init()
</script>
I may be wrong, but it doesn't seem necessary to use PHP just to create an incrementing variable.
You could just write that same for loop in javascript, inside your script tags: I also think using jQuery's slideToggle might make this easier for you... Maybe something along these lines:
for (var i = 1, i <= 5, i++ ){
$(document).ready(function(){
$('divToBeToggled' + i).click(function(){
$('divToBeRevealed' + i).slideToggle('slow');
});
});
}
Just looking quickly at the link you supplied, doesn't this script depend on jQuery also being present? You don't seem to have that script tag in your head tag.
My question is very simple. I want to display only the content of one tr at a time. That means when I click on the other tr then the other opened tr should get closed.
My code is as below
<head>
<style>
p { width:400px; }
.click{cursor:pointer;}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';
}
</script>
</head>
Above is the head section where onClick a function called visibility is getting called. Below in the body section I am trying to display two tr using for loop.
<body>
<table>
<?php
$i=2;
for($i = 1; $i <= 2; $i++)
{
?>
<tr class="click <?php echo $i; ?>" onClick="visibility('<?php echo $i; ?>');">
<td>Click <?php echo $i; ?></td>
</tr>
<tr id="<?php echo $i; ?>" style="display:none;">
<td>This is a paragraph <?php echo $i; ?></td>
</tr>
<?php
}
?>
</table>
</body>
I am unable to get the desired result(That means only one tr should be visible at a time). There are many existing Jquery plugins available but I do not want to use them as it will increase the load on my web page and so much of customization will be required. I am almost done and hoping to get the desired result with the help from you all.
Thanks in advance
Bind a click handler to your tr.click elements, show the corresponding content, and hide the others:
$(this).next('tr').show().siblings().not('tr.click').hide();
Here's a fiddle
You need to set the display to table-row value when displaying the "tr" element.
Let's make use of jQuery.
$(document).on('click', '.clickablerows', function() {
$('.showablerows').css('display','none');
var showee = $(this).data('showee');
$(showee).css('display','table-row');
return false;
});
I'd add/remove a class and handle the visibility state through that so you have more control over what happens with the active/inactive elements (plus you don't have to care if one of the siblings is the clicked element). Also you can use the event delegation of .on() to save some time attaching the event handler.
jsfiddle
JS
var activeClass = 'active';
$('table').on('click', '.click', function() {
$(this).next().addClass(activeClass).siblings().removeClass(activeClass);
});
CSS
td {
display: none;
}
.active td {
display: table-cell;
}
first set class name "test" for all td's
then use this code
$(".test").click(function(){
$(".test").hide();
$(this).show();
});
I put Jquery Tools's Overlay in my site to show a projects' info in several overlays. This works pretty ok, but I have been trying to 'automate' the code to read new projects and load them in overlays. What happen looks ok, but no matter which project I click, the overlays allways load the content of the first project...
I did a lot of googling around and copy-pasting to get this far, I am not (yet) much of a programmer, I hope the code doesn't scare you guys.. ;-)
Anyway, here's a link: http://www.wgwd.nl/test
If you click 'Projects' a normal div opens that loads all the projects it finds (two, for now). When you click one it opens that content in 3 overlays. As said, unfortunately it allways loads the same content independent of which project you click.
I have tried to assign the JScript a unique function name (generated with php from the project's filename) but that doesn't seem to work.
Any ideas? here's my code :
<?
//reads projectfolder and distills
//a basename out of the project description.txt
$textfiles = glob('content/projects/*.txt', GLOB_BRACE);
foreach ($textfiles as $textfile) { ?>
<div id="details"> <?
$pad = pathinfo ($textfile);
$base_name = basename($textfile,'.'.$pad['extension']);
// the link that opens the overlays. Don't think the "id" tag is nescessary
echo '<a id="'.$base_name.'" href="#" onclick="'.$base_name.'()"><img src="'.$base_name.'/main.jpg"/></a>' ?>
<!-- defines overlay, hidden by default -->
<div id="dragwindow1" class="overlay ol1">
<a class="close"></a>
<?
include ('content/projects/'.$base_name.'/content.txt');
?>
</div>
</div>
<?
// the description of each project
include ($textfile);
?>
<script>
// within the foreach open all overlays with function name $base_name
var <?=$base_name?> = function () {
$("a[rel]").each(function() {
$(this).overlay().load();
});
}
</script>
<hr />
<? } //end foreach ?>
</div>
<!-- somehow, without defining these links, the whole 'open all overlay' thing doesn't work -->
<a rel="div.overlay:eq(0)" type="button" style="display: none">first</an>
<a rel="div.overlay:eq(1)" type="button" style="display: none">second</a>
<a rel="div.overlay:eq(2)" type="button" style="display: none">third</a>
<script type="text/javascript">
$(function projects() {
// positions for each overlay
var positions = [
[120, '15%'], //uppper left, #1
[70, '60%'], // lower left, #2
['60%', '40%'], // lower right, #3
];
// setup triggers
$("a[rel]").each(function(i) {
$(this).overlay({
// common configuration for each overlay
oneInstance: false,
// setup custom finish position
top: positions[i][0],
left: positions[i][1],
});
});
});
</script>
Thx in advance!
EDIT: I edited the code to omit all that's unrelated
The question remains: Javascript only returns the content of the first call in the foreach loop. Is there anyway to generate multiple instances of the javascript for each loop in the PHP?
SOLVED! With big, big, help of a friend, who redefined how multiple Overlays from Jquery Tools could work (and should have worked in the first place...)
Without getting too much into it, here's the code for future reference:
Basically the trick is:
// open all overlays
function openAll(currentOverlays) {
$(currentOverlays).each(function()
{
$(this).overlay().load();
});
}
The complete page is now something like this:
<script type="text/javascript">
$(function () {
// positions for each overlay
var positions = [
['60%', 540], // lower right, #3
[80, '65%'], // lower left, #2
[120, '12%'], //uppper right, #1
];
// setup triggers
$("div.overlay").each(function(i) {
$(this).overlay({
// some configuration for each overlay
// positioning the overlays
top: positions[i % 3][0],
left: positions[i % 3][1]
});
});
});
// open all overlays
function openAll(currentOverlays) {
$(currentOverlays).each(function()
{
$(this).overlay().load();
});
}
// close all overlays
function closeAll(currentOverlays) {
$(currentOverlays).each(function()
{
$(this).overlay().close();
});
}
</script>
<div id="projectstarter">
<h2>Projects</h2>
<div class="maindetails">
<a class="close"></a> <!-- defines a close button for the overlay -->
<?
$textfiles = glob('content/projects/*.txt', GLOB_BRACE);
rsort($textfiles);
foreach ($textfiles as $textfile) {
$pad = pathinfo ($textfile);
$base_name = basename($textfile,'.'.$pad['extension']);
echo '<a href="#" onclick="openAll(\'div.'.$base_name.'\')">';
echo '<img src="./content/projects/'.$base_name.'/projectimage.jpg" class="thumb"/></a></div>';
include '$textfile'; //project description
} // end MAIN foreach ?>
</div>
</div>
<div id="projects">
<?
foreach ($textfiles as $textfile) {
$pad = pathinfo ($textfile);
$base_name = basename($textfile,'.'.$pad['extension']); ?>
<div id="dragwindow3" class="<?=$base_name?> overlay ol3">
<a class="close"></a>
<h2>Media</h2>
<div class="details">
// include media here
</div>
</div>
<div id="dragwindow2" class="<?=$base_name?> overlay ol2">
<a class="close"></a>
<h2>Credits</h2>
<div class="details">
// include credits here
</div>
</div>
<div id="dragwindow1" class="<?=$base_name?> overlay ol1 ">
<a class="close"></a>
<h2>Content</h2>
<div class="details">
// include content here
</div>
</div>
<? } ?>
<script>
$( "#projectstarter" ).overlay();
$( "#projectstarter" ).draggable().resizable({ghost: true});
$( ".ol1" ).draggable().resizable({ghost: true});
$( ".ol2" ).draggable().resizable({ghost: true});
$( ".ol3" ).draggable().resizable({ghost: true});
</script>
I have a page with 2 Div containers ( Left and Right ).
PartsList page has 5 dynamically generated DIVS.
Custom page has 5 dynamically generated DIVS.
The div with id "layout" isnt getting recognized with the jQuery .on(). Please help. Thank you for you time :).
<script type="text/javascript" src="js/jquery.js">
</script>
<script type="text/javascript">
$(function() {
$(".left").load("PartsList.php",function() {alert("success");});
$(".right").load("Custom.php", function() {alert("success");});
$("#layout").children().on({click: function() {
alert($(this).attr('id'));
}
});
});
</script>
<body>
<div class="main">
<div class="left">
//Load Left page.
</div>
<div class="right">
//Load Structure page.
</div>
</div>
</body>
</html>
PartsList
<?php
for ($x = 1; $x < 6; $x++)
{
$divs = <<<here
<div id = 'div$x' class = 'list'><strong>Div: $x</strong></div>
here;
echo $divs;
}
?>
Custom
<?php
echo '<div id="layout">';
for ($y = 0; $y < 5; $y++)
{
echo "<div id='x$y' style='
position: absolute;
width: 200px;
height: 100px;
top: ".(100 * $y)."px;
border: 2px solid blue;
cursor: pointer;
'></div>";
}
echo '</div>';
?>
in jquery 1.7+ use on like
$(document).on('click','dynamicElement',function(e){
//handler code here
});
in the earlier versions use delegate
$(document).delegate('dynamicElement','click',function(e){
//handler code here
});
you can replace the document with parent element of the dynamically generated element
From the Jquery online manual:
.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )
url: string containing the URL to which the request is sent.
data: map or string that is sent to the server with the request.
complete(responseText, textStatus, XMLHttpRequest)A callback function that is executed when the request completes.
You probably need to put the .on function as a callback of the .load for that Custom.php page.
Something like this EXAMPLE:
$(function() {
$(".left").load("PartsList.php",function() {alert("success");});
$(".right").load("Custom.php", function() {alert("success");
$("#layout").children().on({click: function() {
alert($(this).attr('id'));
}
});
});
});
I think you've got the wrong syntax for the .on() function it should be something like:
$('document').on('click', '#layout > div', function() {
alert($(this).attr('id'));
});
You bind to the document and when a user clicks on a child div in layout the event 'bubbles' up the DOM to the document where it is caught.
Okay. I found the answer anyhow. For people who were thinking why it didnt work. It was because of the stupid QUOTES.
$("document") should have been $(document) since document isnt a tag <.
And tada thats it.
Sigh.
Thanks for the help everyone :)