I have created an rotating image banner module for an in house CMS. I did not write all the jquery for this and that's why I'm a little confused.
Basically the problem is the first image displayed in the banner after a page reload does not fade out like the rest of the images do. I understand that this probably because it is the default image loaded and is not part of the loop that's causing the image banner to rotate. The banner can be seen here: http://www.easyspacedesign.com/craig/dentalwise/
Notice how the first image after a reload sort just jumps to the next image but then all he images afterwards smoothly fade in and out.
How do I grab that first image after a reload and make it fadeout like rest?
here is the code:
<script type="text/javascript">
<!--
var doLooop = true;
$(document).ready(function(){
setInterval("loop()",5000);
});
function loop(){
if(!doLooop){ return; }
var $total = parseInt($("input[name=total_slides]").val());
var $id = parseInt($("a._active").attr("rel"));
var $new = $id+1;
if($new>$total){$new=1;}
changeSlide($new);
}
function changeSlide($id){
// Prepare selectors
var $total = $("input[name=total_slides]").val();
var $txtSlt = "#_slideText_"+$id;
var $imgSlt = "#_slideImg_"+$id;
var $active = $("a._active").attr("id");
var $new_img_href = "#animation_selectors a:nth-child("+$id+") img";
var $new_active = "#animation_selectors a:nth-child("+$id+")";
// Hide active images and text
$(".slideImg").css("display","none");
$(".slideTxt").css("display","none");
// Display selected images and text
$($txtSlt).fadeIn(1200);
$($imgSlt).fadeIn(1200);
$($txtSlt).delay(2500).fadeOut(1200);
$($imgSlt).delay(2500).fadeOut(1200);
// Update active anchor image
$("a._active img").attr("src","<?php echo ROOT; ?>Images/StyleImages/off.png");
$("a._active").removeClass("_active");
$($new_img_href).attr("src","<?php echo ROOT; ?>Images/StyleImages/on.png");
$($new_active).addClass("_active");
}
$(function(){
$("#animation_selectors a").click(function(e){
e.preventDefault();
var $id = $(this).attr("rel");
doLooop = false;
changeSlide($id);
});
});
-->
</script>
<div id="animation">
<div id="animation_slides">
<?php
$img_sql = "SELECT strImageUrl FROM tbl_mod_Animation ORDER BY intAnimationID";
if($img = $db->get_results($img_sql)){ $i=1;
foreach($img as $img){
if($i!=1){ $display = " style=\"display:none;\""; } else { $display = ""; }
echo "<div id=\"_slideImg_$i\" class=\"slideImg\" $display><img src=\"".ROOT."Images/Uploads/Slides/".$img->strImageUrl."\" alt=\"\" /></div>";
$i++;
}
}
?>
</div>
<div id="animation_text">
<?php
$text_sql = "SELECT strText FROM tbl_mod_Animation ORDER BY intAnimationID";
if($text = $db->get_results($text_sql)){ $i=1;
foreach($text as $text){
if($i!=1){ $display = " style=\"display:none;\""; } else { $display = ""; }
echo "<div id=\"_slideText_$i\" class=\"slideTxt\" $display>".$text->strText."</div>";
$i++;
}
}
?>
</div>
<div id="animation_selectors">
<?php
for($x=1;$x<$i;$x++){
if($x==1){
?><a id="slide_opt<?php echo $x; ?>" href="#" rel="<?php echo $x; ?>" class="_active"><img class="slideOpt" src="<?php echo ROOT; ?>Images/StyleImages/on.png" alt="" /></a><?php
} else {
?><a id="slide_opt<?php echo $x; ?>" href="#" rel="<?php echo $x; ?>"><img class="slideOpt" src="<?php echo ROOT; ?>Images/StyleImages/off.png" alt="" /></a><?php
}
}
echo "<input type=\"hidden\" name=\"total_slides\" value=\"".($i-1)."\" />";
?>
</div>
</div><!--end of animation-->
<?php
?>
changeSlide() sets up each slide to fade in and then fade out in 2.5 seconds. loop() calls changeSlide() every 5 seconds and passes the id of the next slide to be shown. The problem is that the first slide isn't set up the same way on page reload. It's probably just statically written on the page with the _active class.
You'd be better off, instead of setting a delay to fade each slide out after 2.5 seconds, to pass in both the previous and next slide to the changeSlide function and then fade out the previous and fade in the next.
function loop() {
...
changeSlide($id, $new);
}
and then in changeSlide:
function changeSlide($prev, $next) {
...
var $prevTxtSlt = "#_slideText_" + $prev;
var $prevImgSlt = "#_slideImg_" + $prev;
var $nextTxtSlt = "#_slideText_" + $prev;
var $nextImgSlt = "#_slideImg_" + $prev;
...
$($prevTxtSlt).fadeOut(1200);
$($prevImgSlt).fadeOut(1200);
$($nextTxtSlt).fadeIn(1200);
$($nextImgSlt).fadeIn(1200);
}
Related
I am filtering an element from an Ajax Response as :
var storyResults = $(data).filter('#success_stories');
var videoResults = $(data).filter('#success_videos');
if(storyResults.length == 0) {
//hide the Load More button if there are no more records to load
$(".load_more_stories").hide();
$(".load_more_videos").show();
}
if(videoResults.length == 0) {
//hide the Load More button if there are no more records to load
$(".load_more_stories").hide();
$(".load_more_videos").hide();
}
Now I can't do that as :
(storyResults.trim().length == 0)
When I want to do that so I get error as it's array so then how can I trim spaces then from the array element?
Update :
What I want to do is to achieve the length == 0 if I am right about that by removing spaces from the following element would it make it true that the length of the element will be 0 or should I counting the innertext length ?
Here is the element as :
<div id="success_stories"> </div>
The Ajax Data Records are being pulled from this page as :
<?php
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
$item_per_page_story = "30";
$story_start = (($page_number-1) * $item_per_page_story);
$story_end = $page_number * $item_per_page_story;
$item_per_page_video = "11";
$vid_start = (($page_number-1) * $item_per_page_video);
$vid_end = $page_number * $item_per_page_video;
?>
<?php if (array_key_exists($story_start, $clinic_stories)) { ?>
<div id="success_stories">
<?php
for ($i=$story_start; $i < $story_end; $i++) {
if (isset($clinic_stories[$i])) { ?>
<?php $patient_name = $clinic_stories[$i]->getPatientName(); ?>
<?php if ($clinic_stories[$i]->getThumbnail()):?>
<div class="col-md-4">
<a data-featherlight="success/<?php echo $i+1; ?>" href="#">
<span class="thumbnail grow" style="position: relative;left: 0px;top: 0px;">
<img src="<?= "/uploads/" . $clinic_stories[$i]->getThumbnail() ?>" style="width:200px;height:150px;" alt="" />
</span>
</a>
</div><?php endif; ?><?php } } ?></div>
<?php } else { echo '<div id="no_stories"></div>'; } ?>
<?php if (array_key_exists($vid_start, $clinic_videos)) { ?>
<div id="success_videos"><?php
for ($i=$vid_start; $i < $vid_end; $i++) {
if (isset($clinic_videos[$i])) {
$embed = $clinic_videos[$i]->getEmbed();
$pos_vidStart = strpos($embed, "embed/");
$pos_vidEnd = strpos($embed, "\"", $pos_vidStart+6);
$embed = substr($embed, $pos_vidStart+6, $pos_vidEnd - ($pos_vidStart+6));
?>
<div class="success-stories-video-frame">
<input type="hidden" id="vid<?= $i+1; ?>" value="<?= $embed ?>">
<?php if ($clinic_videos[$i]->getThumbnail()):?>
<span class="thumbnail">
<a data-featherlight="reviews/video/id/<?php echo $embed; ?>" data-featherlight-iframe-overflow="hidden" href="#"> <img src="<?= "/uploads/" . $clinic_videos[$i]->getThumbnail() ?>" alt="video file" title="CLICK TO PLAY" /></a>
</span>
<?php endif; ?>
</div><?php } } ?></div>
<?php } else {
echo '<div id="no_videos"></div>';;
} ?>
Also the whole JS code is as follows :
<script type="text/javascript">
var track_page = 1; //track user click as page number, right now page number is 1
load_contents(track_page); //load content
$(".load_more_stories").click(function (e) { //user clicks on button
track_page++; //page number increment everytime user clicks load button
load_contents(track_page); //load content
});
$(".load_more_videos").click(function (e) { //user clicks on button
track_page++; //page number increment everytime user clicks load button
load_contents(track_page); //load content
});
//Ajax load function
function load_contents(track_page){
$('.animation_image').show(); //show loading image
$.post( '<?php echo $url; ?>/get-reviews', {'page': track_page}, function(data){
var storyResults = $(data).filter('#success_stories');
var videoResults = $(data).filter('#success_videos');
if(storyResults.text().trim().length == 0) {
//hide the Load More button if there are no more records to load
alert(storyResults.text());
$(".load_more_stories").hide();
$(".load_more_videos").show();
}
if(videoResults.length == 0) {
//hide the Load More button if there are no more records to load
$(".load_more_stories").hide();
$(".load_more_videos").hide();
}
$("#story_results").append(storyResults); //append data into #results element
$("#video_results").append(videoResults); //append data into #results element
//scroll page to button element
$("html, body").animate({scrollTop: $(".box-content").offset().bottom}, 100);
//hide loading image
$('.animation_image').hide(); //hide loading image once data is received
});
}
</script>
There are some problems with your code, it generates invalid HTML just by the fact that you appending elements with the same IDs (success_stories + success_videos) when you pull the results from the server more than once.
What i'm suggesting is to return an array of objects from the server and create the elements on the client side:
$item_per_page_story = "30";
$story_start = (($page_number-1) * $item_per_page_story);
$story_end = $page_number * $item_per_page_story;
$item_per_page_video = "11";
$vid_start = (($page_number-1) * $item_per_page_video);
$vid_end = $page_number * $item_per_page_video;
$results = array(
'stories' => array(),
'videos' => array()
);
if (array_key_exists($story_start, $clinic_stories)) {
$story = array();
for ($i=$story_start; $i < $story_end; $i++) {
if (isset($clinic_stories[$i])) {
$story['id'] = $i + 1;
$story['patient_name'] = $clinic_stories[$i]->getPatientName();
if ($clinic_stories[$i]->getThumbnail()) {
$story['thumbnail'] = $clinic_stories[$i]->getThumbnail();
}
}
}
array_push( $results['stories'], $story );
}
if (array_key_exists($vid_start, $clinic_videos)) {
$video = array();
for ($i=$vid_start; $i < $vid_end; $i++) {
if (isset($clinic_videos[$i])) {
$video['id'] = $i+1;
$embed = $clinic_videos[$i]->getEmbed();
$pos_vidStart = strpos($embed, "embed/");
$pos_vidEnd = strpos($embed, "\"", $pos_vidStart+6);
$video['embed'] = substr($embed, $pos_vidStart+6, $pos_vidEnd - ($pos_vidStart+6));
if ($clinic_videos[$i]->getThumbnail()) {
$video['thumbnail'] = $clinic_videos[$i]->getThumbnail();
}
}
}
array_push( $results['videos'], $video );
}
echo json_encode( $results );
Next, when you fetch the data from the server, you get an JSON object of the videos and stories returned from the server:
function load_contents(track_page){
$('.animation_image').show(); //show loading image
$.post( '<?php echo $url; ?>/get-reviews', {'page': track_page}, function(data){
// Check the console to see the results from the server
console.log( data );
var storyResults = data.stories;
var videoResults = data.vidoes;
if(storyResults.length == 0) {
//hide the Load More button if there are no more records to load
$(".load_more_stories").hide();
$(".load_more_videos").show();
} else {
// Here we create the elements using jquery
for( var i = 0; i < storyResults.length; i++ ) {
$('<div></div>').addClass("col-md-4").append(
$('<a></a>').attr('data-featherlight', 'success/' + storyResults[i].id).attr('href', '#').append(
$('<span></span>').addClass('thumbnail').addClass('grow').css({
'position': 'relative',
'left': 0,
'top': 0
}).append(
$('<img />').attr('src', '/uploads/' + storyResults[i].thumbnail)
)
)
).appendTo( "#story_results" )
}
}
/// SAME LOGIC FOR videoResults
//scroll page to button element
$("html, body").animate({scrollTop: $(".box-content").offset().bottom}, 100);
//hide loading image
$('.animation_image').hide(); //hide loading image once data is received
});
}
Now if you find it to difficult, you can still create the html on the server side, and just append each HTML to the array. Simplified example:
$results = array(
'stories' => array(),
'videos' => array()
);
for ($i=$story_start; $i < $story_end; $i++) {
$storyHTML = '<div class="col-md-4">
<a data-featherlight="success/' . ($i+1) . '" href="#">
<span class="thumbnail grow" style="position: relative;left: 0px;top: 0px;">
<img src="/uploads/"' . $clinic_stories[$i]->getThumbnail() . '" style="width:200px;height:150px;" alt="" />
</span>
</a>
</div>';
array_push( $results['stories'], $storyHTML );
}
echo json_encode( $results );
And then you just need to loop over the elements on jQuery and append each and every one to the container.
I have in my database 2 rows of information so my code create will create positivoNegativo.png twice and the number 10 twice. When I click on the FIRST positivoNegativo.png my number FIRST 10 is incremented (exacly as I wanted to). Now my issue, when I click on the SECOND positivoNegativo.png, the FIRST number is incremented again! I just can't increment the SECOND number by clicking on the SECOND positivoNegativo.png
<html>
<body>
<?php
include_once("./classe/conexao.php");
$busca = $pdo->prepare("select * from anuncios");
$busca->execute();
$linha = $busca->fetchAll(PDO::FETCH_OBJ);
$classe = 0;
foreach ($linha as $lista) {
echo "<p class='demo'>10</p>";
echo "<img src='imagens/positivoNegativo.png'usemap='#mapa'>";
echo "<map name='mapa'>";
echo "<area shape='rect' coords='1,1,73,59' onclick='aumenta($classe)'>";
echo "</map>";
echo "<span>$lista->titulo</span>";
$classe++;
}
?>
<script>
function aumenta(classe) {
var numero = document.getElementsByClassName('demo')[classe].innerHTML;
numero++;
document.getElementsByClassName('demo')[classe].innerHTML = numero;
}
</script>;
</body>
You need to use different map for each image.
foreach ($linha as $lista) {
echo "<p class='demo'>10</p>";
echo "<img src='imagens/positivoNegativo.png'usemap='#mapa$classe'>";
echo "<map name='mapa$classe'>";
echo "<area shape='rect' coords='1,1,73,59' onclick='aumenta($classe)'>";
echo "</map>";
echo "<span>$lista->titulo</span>";
$classe++;
}
Try this:
<?php
include_once("./classe/conexao.php");
$busca = $pdo->prepare("select * from anuncios");
$busca->execute();
$linha = $busca->fetchAll(PDO::FETCH_OBJ);
$classe = 0;
foreach ($linha as $lista) {
echo "<p class='demo".$classe."'>10</p>";
echo "<img src='imagens/positivoNegativo.png' onclick='aumenta($classe)'>";
echo "<span>$lista->titulo</span>";
$classe++;
}
?>
<script>
function aumenta(classe) {
var numero = document.getElementsByClassName('demo'+classe).innerHTML;
numero++;
document.getElementsByClassName('demo'+classe).innerHTML = numero;
}
</script>;
I didn't test the code, but it might give you some hints.
I left out the whole <map> thing because it doesn't make sense in your code. There's only an up?
I need a fresh pair of eyes to look at this!
I took code directly from one of of my old fiddles https://jsfiddle.net/RachGal/fs9u6mwe/1/ to display photos in a college galley site. However it only shows one. When i include bootstrap and the function in my php it doesn't seem to read it! Why could this be?
My php looks like this
<?php
echo "<html><head><meta charset='utf-8'>";
echo "<script type='text/javascript' src='scripts/bootstrap.js'></script>";
echo"<link rel='stylesheet' type='text/css' href='css/style.css'>";
include "scripts/show.php";
echo" <title>Gallery Display</title></head><body>";
echo "<header>";
echo "<h1>The Ultimate Gallery Compiler</h1>";
echo "<div id='menu'><a class='head' href='index.html'>Upload Photo</a> <a class='head' href='gallery.html'>Browse Gallery</a></div>";
echo "</header>";
echo "<div id='content'>";
echo "<h2>Browse Gallery</h2>";
$subfolder = $_POST["category"];
if ($subfolder == "0"){
echo("Please <a href='gallery.html'>go back</a> and select a category");
echo "</div><br><br>";
echo "<footer>";
echo "<p class='foot'>© Copyright 2015-2016 MMA2 Rachel Gallen, Ysabel Pheifer and Rebecca Merrigan.</p>";
echo "</footer>";
exit();
}
$countcontents = file_get_contents("categories.txt"); //read file to get count
$countarray = explode('*', $countcontents); //get count of each category into an array
$categories = array("fashion", "music", "sports", "technology", "animals", "health", "other");
//output title according to if the gallery has images in it or not
for($i=0; $i< count($countarray); $i++)
{
if ($subfolder == $categories[$i]){
if (intval($countarray[$i]) == 0) {
echo "<h3>No images have been uploaded for the " .$subfolder. " category yet</h3>";
}
else
{
echo "<h3>Here are the images for the " .$subfolder. " category</h3>";
echo "<p>There are ".$countarray[$i]." photos in this category</p><br>";
}
}
}
$folder = "images/".$subfolder."/";
// Open the appropriate subfolder, and display its contents.
// http://php.net/manual/en/function.opendir.php
// also referenced https://www.youtube.com/watch?v=nGLi4ykt__0
if ($dir = opendir($folder)) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
}
}
closedir($dir);
}
echo '<div id="slider">';
echo "<ul id='slides'>";
foreach($images as $image) {
echo '<li class="slide"><img src="';
echo $folder.$image;
echo '" alt=""/></img></li>';
}
echo "</ul>";
echo '</div>';
echo "<p> </p><a href='gallery.html'>Reselect</a>";
echo "</div>";
echo "<footer>
<p class='foot'>© Copyright 2015-2016 MMA2 Rachel Gallen, Ysabel Pheifer and Rebecca Merrigan.</p>
</footer>";
echo "</body></html>";
?>
Any help would be appreciated!
by the way the javascript is
//Reference https://jsfiddle.net/RachGal/fs9u6mwe/1/
$(document).ready(function() {
//INDEX IMAGES SLIDER
$(function slider() {
//configuration
var width = 360;
var speed = 1000;
var pause = 3000;
var current = 1;
//cache DOM
var $slider = $('#slider');
var $slides = $slider.find('#slides');
var $slide = $slides.find('.slide');
setInterval(function() {
//move image the defined width and speed to the left
$slides.animate({
'margin-left': '-=' + width
}, speed, function() {
//count number of slides and loop back to first from last
current++;
if (current === $slide.length) {
current = 1;
$slides.css('margin-left', 0);
}
});
}, pause);
});
}
);
You have not included jQuery in your pages, you are using jQuery in your script but it is not loaded at all.
A nice way to find these things out is using the developer bar by pressing F12 when using chrome, then at network you can see which files were loaded and in console if there were any javascript errors.
I have my triggers and divs to show/hide in a while loop, instead of using div id which has to unique, i've decided to use div class to show/hide a group of content among others.
what i'm trying to achieve:
i'm not at all good with javascript, and i've been trying to achieve this for days. Say i have a trigger with div class="view1-'.$id1.'" where $id1=2 and div class="licom-'.$cc_id.'" where $cc_id=2 to show/hide, is it possible to ensure that my trigger would only show/hide the div class with the same id as 2?.
JavaScript
<html>
<head>
<script language="JavaScript">
$(document).ready(function(){
var showText='View all replies';
var hideText='Hide';
// initialise the visibility check
var is_visible = false;
// append show/hide links
$('.view1').prev().append();
$(".licom").hide();
$(".view1").click(function(){//i need to pass the div class with the variable
// switch visibility
is_visible = !is_visible;
// change the link depending on whether the element is shown or hidden
$(this).html( (!is_visible) ? showText : hideText);
//i also need to pass the right div class with the right variable, and keep the others hidden
$('.licom').toggle(function() {
$(this).closest('view1').find('.licom').hide();
return false;
},
function() {
$(this).closest("view1").next(".licom").show();
return false;
});
});
});
</script>
</head>
<body>
</body>
</html>
info.php
<?php
...........
$stmt = $conn->prepare(
"SELECT *
FROM comment
WHERE post_id = :pid
");
$stmt->bindParam(":pid", $type_id, PDO::PARAM_INT);
$stmt->execute();
while($obj = $stmt->fetch()){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id1 = $obj['id'];
$userimage = $obj['user_image'];
echo '<div class="txt">';
echo '<div class="comment-container">';
echo '<div class="comment-item">';
echo '<div class="comment-avatar">';
echo '<img src="user/user_images/'.$userimage.'" alt="avatar">';
echo '</div>';
echo '<div class="comment-post">';
echo '<span style="font-weight:bold;">'.$username.'  said....
</span>';
echo '<p style="margin-left:-11px;">'.$comment.'</p>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
//trigger to hide/show replies
echo '<span class="view1-'.$id1.'" style="float:right;margin-top:-15px;">View all replies</span>';
//
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
//Relpy to comment, show only the first row
$rep = $conn->prepare("SELECT * FROM reply WHERE comment_id = :comid LIMIT 1");
$rep->bindParam(":pid", $id1, PDO::PARAM_INT);
$rep->execute();
while($obj = $rep->fetch()){
//...........same output as first without the view all replies trigger......
//Relpy to comment, show from row 2-
$rep = $conn->prepare("SELECT * FROM reply WHERE comment_id = :comid LIMIT 1,18446744073709551615");
$rep->bindParam(":pid", $id1, PDO::PARAM_INT);
$rep->execute();
while($obj = $rep->fetch()){
$cc_id = $obj['comment_id'];
//div to show/hide
echo '<div class="licom-'.$cc_id.'">';
//...........same output as first without the view all replies trigger......
}
}
}
?>
how do i re-write my JavaScript so that all div of class "licom" are hidden by default, and only the div with the same id as the trigger say 2,3,... as the case maybe would show/hide onClick.
As requested in the comments on question:
"Something like: http://jsfiddle.net/qjadyznh/ ?"
$('a').click(function(){
var id = $(this).attr('id');
if($('.'+id).css('display') == 'none')
{
$('.'+id).css('display','block');
}
else
{
$('.'+id).css('display','none');
}
})
Simple example on how to achieve the goal needed.
I made a gallery with images fetched from DB and using Fancybox for displaying it. I have some articles that are the same, just diferent color and I display just one and underneath color boxes for changing the color.
The problem is that when I click on the button to change the color, picture changes, Fancybox on click displays first picture, not the Current one
Part of the code:
JS:
function changeImage(element,id){
var img=document.getElementById(id).src=element;
return false;
}
PHP:
while($row = mysql_fetch_array($sql)){
$prikaz =$row['prikaz'];
$id = $row['id'];
$ime = $row['ime'];
$thumb = $row['thumbs'];
$boja = $row['boja_id'];
$slicka = $row['slika'];
$spec = $row['tekst'];
if ($prikaz == 1){
echo "<table style ='display: inline' align='center'>";
echo "<tr>";
echo "<td><a class='fancybox-effects-a' href='$slicka' ><img id='$id' src='$thumb' alt='' /></a></td>";
echo "</tr>";
echo "<tr><td>";
echo "Boja: ";
$bsql = mysql_query ("SELECT muski.tekst, muski.id,muski.thumbs,boja.bslika FROM boja INNER JOIN muski ON muski.boja_id = boja.id WHERE muski.ime = '$ime' " );
while($res = mysql_fetch_array($bsql)){
$slicica = $res['thumbs'];
$muid = $res['id'];
$kockica = $res['bslika'];
echo "<button id = 'boja' onclick =changeImage('$slicica','$id')><img src= $kockica ></button>";
}
echo "</br>";
echo nl2br($spec);
}
echo "</td>";
echo "</tr>";
echo "</table>";
I found the solution.... I modified js script to change the parent href of img... It works...
function changeImage(element,id,staza) {
var img = document.getElementById(id);
img.src= element;
img.parentNode.href=staza;
return false;
}
Firebug your Fancy Box pop-up and inside the you have to change back ground image as well