I have an auto-generated form that also handily displays thumbnails. I want to add a button beside the image that will refresh it if it is updated. I want to take cached images into account.
I add a button easily enough:
// add a refresh button to image previews
$('a[href*="/thumbs/"]').after('<div class="refresh-image"><button class="refresh-image-button">Refresh</button></div>');
And since I'm okay if the refresh button refreshes all of the stale images I try to append a query string to the image src (deleting an old query string if it exists):
// attach refresher to button
$(".refresh-image-button").click(function() {
$('img[src*="/thumbs/"]').attr("src", $(this).attr("src").split('?',1)+'?'+Date.now());
});
However, I can't really do this because here $(this) doesn't refer to the matched image, and I can't do a split operation within this jquery match anyway.
How do I do it?
As a bonus if anyone has a ref to decent auto refresh image code, that would be helpful.
This builds on a simpler SO inquiry here.
Iterate through the collection:
$(".refresh-image-button").click(function() {
$('img[src*="/thumbs/"]').each(function() {
$(this).attr("src", $(this).attr("src").split('?',1)+'?'+Date.now());
});
});
http://jsfiddle.net/g68gxu93/1/
You could generate a variable with the new trailing parameter separately like :
$(".refresh-image-button").click(function() {
var newAttr = $('img[src*="/thumbs/"]').attr("src").split("?")[0] + "?ver=" + new Date().getTime();
$('img[src*="/thumbs/"]').attr("src", newAttr);
});
see JSFIDDLE
I ended up doing something almost precisely like #Moogs answer.
addRefreshButtons();
// NICEITIES
function addRefreshButtons() {
// add a refresh button to image previews
$("div.refresh-image").remove();
$('a[href*="/thumbs/"]').after('<div class="refresh-image"><button class="refresh-image-button">Refresh</button></div>');
// attach refresher to button
$(".refresh-image-button").click(function() {
refreshThumbnails();
});
}
function refreshThumbnails() {
$('img[src*="/thumbs/"]').each(function() {
var src = $(this).attr('src');
var newSrc = src.split('?',1)+'?'+Date.now()
$(this).attr('src', newSrc);
});
}
Related
I am currently running JavaScript in my html document successfully which allows me to swap a main-img on hovering over various thumbnails. I have these successfully working in various modal windows with different selections of images within each modal window.
My issue is that after I hover over an image and the 'main-img' changes to the respective thumbnail, When I then then close this window and open a different modal window the 'main-img' has remained that from the previous swap in the previous modal window.
this is the javascript being used for the 'image swap':
$(document).ready(function() {
// Image swap on hover
$("div#gallery li img").hover(function() {
$('img#main-img').attr('src', $(this).attr('src').replace('thumb/', ''));
});
// Image preload
var imgSwap = [];
$("div#gallery li img").each(function() {
imgUrl = this.src.replace('thumb/', '');
imgSwap.push(imgUrl);
});
$(imgSwap).preload();
});
$.fn.preload = function() {
this.each(function() {
$('<img/>')[0].src = this;
});
}
I attempted to fix the issue by creating a secondary script which reloads or resets the 'main-img's source back to the original for each modal on a button click which opens the respective modals. However I am only recently self learning jquery and java-script so haven't got to grips with the complexities of the code so there are likely some obvious errors or better ways to approach this.
$(document).ready(function() {
// script reset and reload
$("button.md-trigger").click(
function(){
$('img#main-img').attr('src','2.jpg');
});
});
If you need any more information please let me know.
updated code still not working :
$(document).ready(function() {
var $mainImg = $('img#main-img');
$mainImg.data('originalSrc', $mainImg.attr('src'));
$("div#gallery li img").hover(function(){
$mainImg.attr('src',$(this).attr('src').replace('thumb/', ''));
});
$("button.md-trigger").click(
function(){
$mainImg.attr('src', $mainImg.data('originalSrc'));
});
}
Save it off into a data element.
var $mainImg = $('img#main-img');
$mainImg.data('originalSrc', $mainImg.attr('src'));
$("div#gallery li img").hover(function(){
$mainImg.attr('src',$(this).attr('src').replace('thumb/', ''));
});
Then when you want to change it back, replace the src with the $mainImg.data('originalSrc')
I have 12 buttons each with an ID, i'm using this script for the action.
$(document).ready(function() {
$("#WEyear18000").click(function() {
$("#WEtextarea").load("Files/Docs/y18000.txt");
$('#WEimage_view').html('<img src="Files/Image/treesimages/PalaeoGlaciolMaps.jpg" >');
$('#WEee244f5837 .PullZone').click();
wheelzoom(document.querySelectorAll('img'));
});
});
WEyear18000, is the id of button, WEtextarea, is the id of the div where txt is displayed on button click, WEimage_view, is the id of the div where new image displayed on same button click, WEee24f5837, is the id to close a collapsible panel where buttons are located.
There are 12 of these script statements in a .js file.
It all works but it causes some strange effects after the 2nd or another button is clicked, all the images on the page disappear but the one on the button click. Page is here, page with issue
Any suggestion on how to stream line script wanted. I a newbe to scripting but managed to hodgepodge this to work but has and adverse affect on the rest of the pages images. Suggestion and samples to jsfiddle. Thanks in advance.
<div id="wrapper">
<div id="WEtextarea"> </div>
<div id="WEimage_view"></div>
</div>
CSS controls size and all aspects of div.
I tried all your menu items... And did not notice such a bug.
So, while your're here... I have a suggestion to reduce your long script made of a small chunk repeated 12 times.
I would define the maps as objects, like this:
var maps = [
{
buttonId: "WEyear18000",
text: "Files/Docs/y18000.txt",
image: "Files/Image/treesimages/PalaeoGlaciolMaps.jpg"
},
{
// other 11 objects using the same structure...
}
];
And I would just add a class to each items, in the HTML, like this:
<div id="WEyear18000" class="BaseDiv RBoth OEWELinkButton OESK_WELinkButton_Default OECenterAH clickHandlerClass" style="z-index:1">
Then, I would use a shorter function like this one:
$(document).ready(function() {
$(".clickHandlerClass").click(function(){
// Get the id of the clicked menu item
var thisId = $(this).attr("id");
// Find its related object
var mapIndex = -1;
for(i=0;i<maps.length;i++){
if( maps[i].buttonId == thisId ){
mapIndex = i;
}
}
if(mapIndex != -1){
// Use the object infos in the page elements.
$("#WEtextarea").load(maps[mapIndex].text);
$('#WEimage_view').html('<img src="'+maps[mapIndex].image+'" >');
$('#WEee244f5837 .PullZone').click();
wheelzoom(document.querySelectorAll('img'));
}else{
console.log("Undefined map or id error...");
}
});
});
The array of objects is way easier to maintain... And an additional button easier to add.
You can use another class name than "clickHandlerClass".
;)
The wheelzoom looked like the only possible source of error to me. So I looked for its source, and found:
Wheelzoom replaces an img's background-image with its src. Then the src is set to a transparent image.
So, on the first wheelzoom, you get src transeparent, and on the second, you get a transparent background-image as well.
You can fix this by calling wheelzoom only on your new image:
$(document).ready(function() {
$("#WEyear18000").click(function() {
$("#WEtextarea").load("Files/Docs/y18000.txt");
$('#WEimage_view').html('<img src="Files/Image/treesimages/PalaeoGlaciolMaps.jpg" >');
$('#WEee244f5837 .PullZone').click();
//wheelzoom(document.querySelectorAll('img'));
wheelzoom(document.querySelectorAll('#WEimage_view img'));
});
to fix your bug you need to replace:
wheelzoom(document.querySelectorAll('img'));
with:
wheelzoom(document.querySelectorAll('#WEimage_view img'))
So only the images in the #WEimage_view will be affected by wheelzoom
So I have this button, and when its clicked an image is shown, but if the page is refreshed the image disappears, and I don't want that. How do i get the image to stay even when the page refreshes.
here is my image show function:
<script>
function showImage()
{
$("#loadingImage").show();
};
</script>
and here is my button:
<input name="Failure Analysis Lab" style="white-space:normal;"
onclick="moveText(this.name);showImage();form1.submit() "
style="width: 272px; height: 30px;" type="button"
value="7QKD Failure Analysis Lab" />
You can set and get a cookie like this on your button click:
$.cookie("showImage", true);
Then do the following:
$(document).ready(function()
{
var image = $('#loadingImage');
if($.cookie('showImage') {
image.addClass('image-visible');
} else {
image.show();
}
});
CSS
.image-visible {display: block}
You can use sessionStorage for this.
In your init:
var isImage = sessionStorage.getItem('isImage');
if (isImage !== null) showImage();
function showImage() {
sessionStorage.setItem('isImage', '1');
$("#loadingImage").show();
};
If the image has been shown a value is stored in the temporary storage (will be erased when browser is closed - if you want it to be permanent use localStorage instead. Support goes back to IE8). Then on refresh the value is checked for and if exists the image will be shown.
You can use history.pushState() to add a hash or a parameter to the current page. When the page loads or reloads you can check for the presence and show the image initially
var hstate = {}; // state object you may or may not want to use
history.pushState( hstate, 'Page Title', '#img' );
// -- or --
history.pushState( hstate, 'Page Title', '?img=true' );
If needed you can get the current URL first so you can preserve existing parameters or hashes when you add your own.
To support older browsers use a polyfill such as History.js, as mentioned in another question.
Here's what I have so far, which allows the user to click an image to open a new window and go to a location. When that click occurs, the image in the parent window is replaced with the next div.
Example: http://jsfiddle.net/rzTHw/
Here's the working code so far...
<div class = "box"><img src="http://placehold.it/300x150/cf5/&text=img+1"></div>
<div class = "box"><img src="http://placehold.it/300x150/f0f/&text=img+1"></div>
<div class = "box"><img src="http://placehold.it/300x150/fb1/&text=img+1"></div>
<div class = "box"><img src="http://placehold.it/300x150/444/&text=img+1"></div>
Jquery:
$('.box').not(':first').hide();
$('.box a').click(
function(e){
e.preventDefault();
var newWin = window.open(this.href,'newWindow'),
that = $(this).closest('.box'),
duration = 1200;
if (that.next('.box').length){
that.fadeOut(duration,
function(){
that.next('.box').fadeIn(duration);
});
}
});
What I am having trouble with is:
Creating a "next" button so the user can cycle through to the next div without having the click the image, thus avoiding having to open a new window to get to the next image.
Having a click on the last div redirect the window location to a URL, while still doing the normal function of opening a new window to the a href location if the image is clicked. Otherwise if clicking the "next" button when the last div is shown, simply redirect the user.
What's the best way to go about this? Thanks!
Here is my attempt at tweaking your code to allow for a next button, and my best guess at what you want to happen for the last image:
var redirectUrl = 'http://www.google.com'; // replace in your code
function next(event, duration) {
duration = duration || 1200; // default value
var that = $('.box:visible');
if (that.next('.box').length) {
that.fadeOut(duration, function() {
that.next('.box').fadeIn(duration);
});
} else {
window.location.href = redirectUrl;
// the above line doesn't work inside jsFiddle, but should on your page
}
return false;
}
$('.box').not(':first').hide();
$('.box a').click(
function(e) {
e.preventDefault();
var newWin = window.open(this.href, 'newWindow'),
duration = 1200;
next(e, duration);
});
$('.next').click(next);
jsFiddle example here. Note the redirect is prevented in some browsers since it is running inside an iframe. But it should work in a normal page.
Perhaps look at a slideshow jquery plugin. JQuery Cycle being just one example. There are plenty. Just google jquery Slideshow or jquery cycle and pick the one that suites you best. The cycle plugin itself has a number of "pager" examples that let you change the contents of the displayed picture without leaving the page.
Most of them offer having the contents be html and not just a simple picture so you can play around with what exactly you want.
There's also Fancybox, lightbox, colorbox, etc. if that's what you're trying to accomplish.
I have a large image in a gallery that needs to change when one of the thumbnails is clicked within a unordered list below. The images are coming in dynamically so the jquery script needs to be able to take the src of the thumbnail, remove "-thumb" from the filename, and then replace the large image with the new source.
Please let me know what is my best approach to a gallery like this.
Thanks in advance.
-B
Something like:
$('img.thumb').click(function() {
var src = $(this).attr('src');
$('#bigImage').attr('src', src.replace(/-thumb/,''));
});
The below examples apply if your thumbs are being loaded in via ajax:
(1) Using Events/live:
$('img.thumb').live("click", function() {
var src = $(this).attr('src');
$('#bigImage').attr('src', src.replace(/-thumb/,''));
});
(2) As a callback to one of jQuery's ajax methods (e.g.):
function initThumbs()
{
$('img.thumb').click(function() {
var src = $(this).attr('src');
$('#bigImage').attr('src', src.replace(/-thumb/,''));
});
}
$('#thumbsDiv').load('thumbs.php?p=2', initThumbs);
karim79's answer could be shortened slightly:
$('img.thumb').click(function() {
$('#bigImage').attr('src', $(this).attr('src').replace(/-thumb/,''));
});
But otherwise, good answer!
The only addition to karim79's is:
In a case the thumbnails are placed within same parent binding an event on that parent would be much better (elegant?) solution that binding events on all thumbnails. The event is propagated, so you can find thumbnails by checking event target.
$().ready(function() {
//get all images from unordered list and apply click function
$('ul#myList img').each(function() {
$(this).click(function() {
$('#mainImage').attr('src', $(this).attr('src').replace('-thumb', ''));
});
});
});