I having trouble getting my caption to show up in my lightbox - javascript

I have a lightbox and i have it able to scroll from one image to another, but since adding the forward and back buttons i lost my caption that used to be there. If anyone could help me figure it out i would appreciate it.
var $overlay = $('<div id="overlay"></div>');
var $image = $("<img>");
var $caption = $("<p></p>");
//An image to overlay
$overlay.append($image);
var $leftArrow = $("<div id='leftArrow'></div>");
var $rightArrow = $("<div id='rightArrow'></div>");
var $closeLightbox = $("<div id='closeLightbox'></div><div style='clear:both'></div>");
$image.before($closeLightbox);
$image.before($leftArrow);
$image.after($rightArrow);
//A caption to overlay
$overlay.append($caption);
//Add overlay
$("body").append($overlay);
//Capture the click event on a link to an image
$("#boxCabinet a,#channelLetters a, #customSignage a, #postandpanel a").click(function(event){
event.preventDefault();
getCurrentImage(this);
//Show the overlay.
$overlay.show();
});
$leftArrow.click(function(){
getPrevImage();
});
$rightArrow.click(function(){
getNextImage();
});
function getCurrentImage (currentImage) {
thisImage = currentImage;
var imageLocation = $(currentImage).attr("href");
//Update overlay with the image linked in the link
$image.attr("src", imageLocation);
//Get child's alt attribute and set caption
var captionText = $(this).children("img").attr("alt");
$caption.text(captionText);
}
function getPrevImage() {
imageParent = $(thisImage).parent().prev();
if(imageParent.length!=0){
thisImage = $(imageParent).children("a");
}
getCurrentImage(thisImage);
}
function getNextImage() {
imageParent = $(thisImage).parent().next();
if(imageParent.length!=0){
thisImage = $(imageParent).children("a");
}
getCurrentImage(thisImage);
}
//When overlay is clicked
$closeLightbox.click(function(){
//Hide the overlay
$overlay.hide();
});
And heres my html
<div id="slideshow">
<a name="featured" id="featured"></a>
<h1>Featured Work</h1>
<div id="ssouter">
<% csv.each do |row|%>
<% if row[2] == "Active" && row[4] == "Featured" %>
<img class="slideshow" src=<%= row[0]%> >
<% end %>
</div>
</div>
<div id="portfolio">
<a name="boxCabinet"></a>
<h1>Box Cabinet </h1>
<ul id="boxCabinet">
<% csv.each do |row|%>
<% if row[3] == "Box" && row[2] == "Active" %>
<li><img src=<%= row[0]%> width="120" height="120"alt="<%=row[1]%>"></li>
<% end %>
<% end %>
</ul>

I fixed it my problem was here.
//Get child's alt attribute and set caption
var captionText = $(this).children("img").attr("alt");
$caption.text(captionText);
}
I accidentally changed $(this).children when it should be $(currentImage).children
currentImage is when/where the caption is needing to be called so I see my error now.It came to me in my sleep, totally forgot til I started working on my code a few minutes ago.

All you'd have to do is to make title attribute of image links use image captions instead of link titles. It would require some modifications in your theme I guess, but the end result should be like that:
<img src="...">
Getting image captions for your attachments is quite well described: here

Related

Fade transition for jquery image swap

I'm somewhat new to jquery and I have this working function that swaps images on the hover of a list element. I am trying to add a fadeOut and fadeIn but its not working. The image fades out, but it doesn't get the correct path for the new image.
This is the working script:
$(document).ready(function() {
var path = 'images/';
$('.menu-child').hover(function() {
var newimage = $(this).attr('data-path') + '.jpg';
$('.swap > img').attr('src', path + newimage)
});
});
This is what I tried for fade effect (and a couple of variations, none of which I could get to work):
$(document).ready(function() {
var path = 'images/';
$('.menu-child').hover(function() {
var newimage = $('.menu-child').attr('data-path') + '.jpg';
$('.swap > img').fadeOut(function() {
$('.swap > img').attr('src', path + newimage).fadenIn();
});
});
});
HTML:
<section class="submenuWrapper">
<ul class="twinsub">
<li class="twinmultisub twinleft">
<ul>
<li class="menu-child" data-path="menu-interior"><span>Interior Painting</span></li>
<li class="menu-child" data-path="menu-exterior"><span>Exterior Painting</span></li>
</ul>
</li>
<li class="twinmultisub twinimg">
<section class="swap">
<img src="images/menu-exterior.jpg" />
</section>
</li>
</ul>
</section>
There we a couple of things.
Try this:
$(document).ready(function() {
var path = 'images/';
$('.menu-child').hover(function() {
var newimage = $(this).attr('data-path') + '.jpg';
$('.swap > img').fadeOut(function() {
$(this).attr('src', path + newimage).fadeIn();
});
});
});
Working Example: https://jsfiddle.net/sabrick/fudLgqxs/3/
You'll probably be able to figure out why it works now on your own, but let me know if you'd like any additional details.
Here is a sample with appropriate comments
$(document).ready(function() {
var path = 'images/';
$('.menu-child').hover(function() {
var newimage = $(this).attr('data-path') + '.jpg';
if(newimage != (path + $('.swap > img').attr('src'))){
/*if the current image being displayed is not the same
as the data-path of the hovered element.
This prevents it from running even when the image should
not be changing
*/
$('.swap > img').fadeOut(0);
//first fade out the current image
$('.swap > img').attr('src', path + newimage);
//then change the path when it is not visible
$('.swap > img').fadeIn(500);
//then fade in the new image with the new path
}
});
});

Image Swap -- Uncaught TypeError: Cannot set property 'src' of null

I'm working through the textbook for a class as I usually do for practice. I'm currently working on an image swapping page where clicking on a thumbnail "swaps" out the main image. The images when clicked become enlarged as if it were a link to another web page. My code is exactly as it is in the book but I get an error. The code is:
var $ = function(id){
return document.getElementById(id);
};
window.onload = function(){
var listNode = $("image_list");
var captionNode = $("caption");
var imageNode = $("main_image");
var imageLinks = listNode.getElementsByTagName("a");
// process image links
var i, image, linkNode, link;
for (i = 0; i < imageLinks.length; i++){
linkNode = imageLinks[i];
// preload image
image = new Image();
image.src = linkNode.getAttribute("href");
// attach event handler
linkNode.onclick = function(evt){
link = this; // "this" is the link that was clicked
// set new image and caption
// the image selected is the "href" and the caption is the title of each image link
imageNode.src = link.getAttribute("href");
captionNode.firstChild.nodeValue = link.getAttribute("title");
// cancel the default action of the event
if (!evt){
evt = window.event;
}
if (evt.preventDefault){
evt.preventDefault();
}else{
evt.returnFalse = false;
}
};
}
// set focus on first image link
imageLinks[0].focus();
};`
The error is thrown at imageNode.src = link.getAttribute("href");
My HTML is:
<body>
<h1>Image Swap With JavaScript</h1>
<p>Click on an image to enlarge.</p>
<ul id="image_list">
<li><a href="images/photo1.jpg" title="Golden Gate">
<img src="thumbnails/thumb1.jpg" alt=""></a></li>
<li><a href="images/photo2.jpg" title="Rocky Coast">
<img src="thumbnails/thumb2.jpg" alt=""></a></li>
<li><a href="images/photo3.jpg" title="Ocean Side">
<img src="thumbnails/thumb3.jpg" alt=""></a></li>
</ul>
<h2 id="caption">Ocean Side</h2>
<p><img id="main-image" src="images/photo3.jpg" alt=""></p>
</body>
Why am I getting this error?
Answer first,then lecture... the mistake in your code is,
<p><img id="main-image" src="images/photo3.jpg" alt=""></p> // from html
var imageNode = $("main_image"); // from javascript
id's don't match, its a simple typo, main_image (never equals) main-image
either use
<p><img id="main-image" src="images/photo3.jpg" alt=""></p> // from html
var imageNode = $("main-image"); // from javascript
or
<p><img id="main_image" src="images/photo3.jpg" alt=""></p> // from html
var imageNode = $("main_image"); // from javascript
Now to understand such typos, pay attention to your code and variables... happy coding :)

How do i let user keep clicking on an image and change the image

This is my javascript: It basically allows users to click on the second image (thermometer) and it will change to a slightly higher temperature AND at the same time, the beaker will be changed too accordingly. How do i let the user keep on clicking and the image to respond accordingly?
$(document).ready(function () {
$("#image").click(function () {
//when image is clicked, change image
var img2 = document.getElementById('image2');
img2.src = "images/beaker1.png";
var img = document.getElementById('image');
img.src = "images/t1.png";
return false;
});
});
Html file:
<div class="col-sm-6">
<img id="image2" src="images/beaker0.png" class="img-rounded">
<img src="images/saturated_percipitate_1.png" class="img-rounded">
</div>
<div class="col-sm-6">
<p><b>Increase Temperature</b></p>
<img id="image" src="images/t0.png" class="img-rounded"/>
<p><b>Decrease Temperature</b></p>
</div>
</div>
If I understand you correctly, maybe this what you are looking for.
The idea is to use counter for current image shown.
$(document).ready(function () {
var indexImage = 1;
$("#image").click(function () {
//check if thermometer is at max.
if(indexImage > 13){ //13 is example maximum value.
return false;
}
//when image is clicked, change image
var img2 = document.getElementById('image2');
img2.src = "images/beaker" + indexImage + ".png";
var img = document.getElementById('image');
img.src = "images/t" + indexImage + ".png";
indexImage++;
return false;
});
});
Add a class notSelected to your image
<img id="image2" src="images/beaker0.png" class="img-rounded notSelected">
then try toggling this class and add src attribute depending on a certain class. This should work:
$("#image").on('click',function(){
$("#image2").toggleClass("selected notSelected");
// change image
$("img.selected").attr('src','images/beaker1.png');
$("img.notSelected").attr('src','images/t1.png');
});
Hope this helps.

Jquery selects second to last child

An interesting thing has happened as I build an light box using Jquery. I've set up left and right arrow buttons to move through the list so that at the last child the right arrow button begins again from the first child or at the first child, the left arrow button moves to the last child.
What's happening is that my left arrow button is supposed to move from the first child to the last child but instead is skipping over the last child and displaying the photo of the second to last child. I'm not having the same problem with the right arrow button moving from the last child to the first.
Also, when I click the left arrow and console.log the last child, I get the very image that I want to display logged correctly, but the image in the overlay is the second to last image.
<body>
<h1>Image Gallery</h1>
<ul id="imageGallery">
<li>
<a href="images/refferal_machine.png">
<img src="images/refferal_machine.png" width="100" alt="Refferal Machine By Matthew Spiel">
</a>
</li>
<li><img src="images/space-juice.png" width="100" alt="Space Juice by Mat Helme"></li>
<li><img src="images/education.png" width="100" alt="Education by Chris Michel"></li>
<li><img src="images/copy_mcrepeatsalot.png" width="100" alt="Wanted: Copy McRepeatsalot by Chris Michel"></li>
<li><img src="images/sebastian.png" width="100" alt="Sebastian by Mat Helme"></li>
<li><img src="images/skill-polish.png" width="100" alt="Skill Polish by Chris Michel"></li>
<li><img src="images/chuck.png" width="100" alt="Chuck by Mat Helme"></li>
<li><img src="images/library.png" width="100" alt="Library by Tyson Rosage"></li>
<li><img src="images/boat.png" width="100" alt="Boat by Griffin Moore"></li>
<li><img src="images/illustrator_foundations.png" width="100" alt="Illustrator Foundations by Matthew Spiel"></li>
<li><img src="images/treehouse_shop.jpg" width="100" alt="Treehouse Shop by Eric Smith"></li>
</ul>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/app.js" type="text/javascript" charset="utf-8"></script>
</body>
The JavaScript:
var $overlay = $('<div id="overlay"></div>');
var $image = $('<img>');
var $caption = $('<p></p>');
var $arrowLeft = $('<button id="left" class="arrow">‹</button>');
var $arrowRight = $('<button id="right" class="arrow">›</button>');
var $exit = $('<button id="exit">X</button>');
//Add image to overlay
$overlay.append($image);
//Add buttons to overlay
$overlay.append($arrowRight);
$overlay.append($arrowLeft);
$overlay.append($exit);
//Add caption to overlay
$overlay.append($caption);
//Add overlay
$('body').append($overlay);
//Capture the click event on a link to an image
$('#imageGallery a').click(function(event) {
event.preventDefault();
var imageLocation = $(this).attr("href");
//Update overlay with the image linked in the link
$image.attr('src', imageLocation);
//Show the overlay
$overlay.show();
//Get child's alt atribute and set caption
var captionText = $(this).children('img').attr('alt');
$caption.text(captionText);
});
//When left arrow is clicked
$arrowLeft.click(function() {
$('#imageGallery li a img').each(function() {
var galleryImage = $(this);
if (galleryImage.attr('src') === $image.attr('src')) {
var li = galleryImage.parent().parent();
if (li.is(':first-child')) {
var gallery = li.parent();
var lastLi = gallery.children(':last-child');
var anchor = lastLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('src'));
console.log(lastLi);
} else {
var prevLi = li.prev();
var anchor = prevLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('src'));
return false;
}
}
});
});
//When right arrow is clicked
$arrowRight.click(function() {
$('#imageGallery li a img').each(function() {
var galleryImage = $(this);
if (galleryImage.attr('src') === $image.attr('src')) {
var li = galleryImage.parent().parent();
if (li.is(':last-child')) {
var gallery = li.parent();
var firstLi = gallery.children(':first-child');
var anchor = firstLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('src'));
} else {
var nextLi = li.next();
var anchor = nextLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('src'));
return false;
}
}
});
});
//When x button is clicked
$exit.click(function() {
//Hide the overlay
$overlay.hide();
});
Update 1:
In the handler, you are running an each loop to test each image element, so make sure return false; is used when you find the matching image, otherwise your loop runs one more time after a match:
//When left arrow is clicked
$arrowLeft.click(function() {
$('#imageGallery li a img').each(function() {
var galleryImage = $(this);
if (galleryImage.attr('src') === $image.attr('src')) {
var li = galleryImage.parent().parent();
if (li.is(':first-child')) {
// if code block
...
} else {
// else code block
...
}
// move this to here
return false;
}
});
});
Make sure to update the arrow right handler as well.
You have an incorrect variable in your click handler:
//When left arrow is clicked
$arrowLeft.click(function() {
if (li.is(':first-child')) {
var gallery = li.parent();
var lastLi = gallery.children(':last-child');
var anchor = lastLi.children('a');
var image = anchor.children('img');
$image.attr('src', image.attr('href'));
console.log(lastLi);
} else {
...
});
Should be:
$image.attr('src', image.attr('src'));
You should look into joining that logic into one handler function to reduce the amount of code.
Also you can simplify this:
var li = galleryImage.parent().parent();
to this:
var li = galleryImage.closest('li');

jQuery custom Image gallery logic

I've tried to customise colorbox on this page so that the main image display launches colorbox, but clicking any of the thumbs just swaps the image into the main image display. This is working fine but one niggling issue is best to handle the indexing/numbering - as I don't want the same image to appear twice in the lightbox image group, and I also want the correct index of the image to show and for the sequence to correspond with the thumbnail sequence. If anyone could see how to improve what I have at the moment that would be great.
The JS I currently have is:
$j(document).ready(function(e) {
function initColorbox() {
$j(".product-gallery").colorbox({
rel : "product-gallery",
current : function() {
var currImg = $j(this).attr("href");
// Grab basename, as initial main image url can differ from corresponding thumb url
var baseName = currImg.replace(/^.*\/|\.[^.]*$/g, '');
var pos;
var total = $j(".more-product-views li a").length;
// Check index by searching for filename in list items
$j(".more-product-views li a").each(function() {
if ($j(this).attr("href").indexOf(baseName) != -1) {
pos = $j(this).parent().index();
}
});
return "" + (pos + 1) + " of " + total;
},
onOpen : updateGallery,
onComplete : function() {
$j("#cboxTitle").hide();
}
});
}
function updateGallery() {
// Remove main product image's corresponding thumb from colorbox group to prevent duplication
var mainProdImg = $j(".main-prod-img").attr("href");
// Grab basename, as initial main image url can differ from corresponding thumb url
var mainProdBaseName = mainProdImg.replace(/^.*\/|\.[^.]*$/g, '');
$j(".more-product-views li a").each(function() {
if ($j(this).attr("href").indexOf(mainProdBaseName) != -1) {
$j(this).removeClass("product-gallery");
} else {
$j(this).addClass("product-gallery");
}
});
// Re-init gallery
initColorbox();
}
initColorbox();
updateGallery();
$j(".prod-more-view").click(function() {
var imgFull = $j(this).attr("href");
$j(".product-image a").attr("href", imgFull);
$j(".product-image img").attr("src", imgFull);
return false;
});
});
you can init the colorbox and use the .click of the ".product-gallery" like they do on the colorboxFAQ
var $gallery = $("a[rel=gallery]").colorbox();
$("a#openGallery").click(function(e){
e.preventDefault();
$gallery.eq(0).click();
});
to change the ".main-prod-img" when you click on the ".product-gallery" and only trigger the colorbox when click on ".main-prod-img" you need to check for event.originalEvent if it is not undefined then you return false
var $j = jQuery.noConflict();
$j(document).ready(function(e) {
//Create the colorbox
var $gallery = $j(".product-gallery").colorbox({
rel:"product-gallery",
onComplete : function() {
$j("#cboxTitle").hide();
}
});
//open colorbox on the right image
$j(".main-prod-img").click(function(e){
e.preventDefault();
var currImg = $j(this).attr("href");
var baseName = currImg.replace(/^.*\/|\.[^.]*$/g, '');
var pos;
var total = $j(".more-product-views li a").length;
$j(".more-product-views li a").each(function() {
if ($j(this).attr("href").indexOf(baseName) != -1) {
pos = $j(this).parent().index();
}
});
$gallery.eq(pos).click();
});
//change .main-prod-img src if e.originalEvent is not undefined or open the color box
$gallery.click(function(e) {
var imgFull = $j(this).attr("href");
$j(".product-image a").attr("href", imgFull);
$j(".product-image img").attr("src", imgFull);
if(e.originalEvent){
return false;
}
});
});
on $j(".main-prod-img").click you need to search for the index of the image in list items and trigger the right ".product-gallery" click like this $gallery.eq(pos).click();
the HTML
<div class="wrapper">
<div class="product-img-box">
<p class="product-image product-image-zoom">
<img src="ohoopee3.jpg">
</p>
<div class="more-views">
<ul class="more-product-views">
<li>
<img src="ohoopee3.jpg" width="56" height="56">
</li>
<li>
<img src="ohoopee2.jpg" width="56" height="56">
</li>
<li>
<img src="ohoopee1.jpg" width="56" height="56">
</li>
<li>
<img src="marylou.jpg" width="56" height="56">
</li>
</ul>
</div>
</div>
</div>
http://jsfiddle.net/bq2fW/

Categories