changing the image src attr - javascript

Looking for some direction with this.
At this current iteration, I have it where if a user clicks on an image thumbnail, the thumbnail image displays in a different div (the main div) and in doing so, it rewrites the main div img src attr *update: with the thumbnail img attr minus the "-thumbnail". This part is good, or at least I believe it is.
With that said, after the user clicks on a thumbnail and the main div img appears, it lingers...and what I mean by lingers is that for example, if a user closes the div and re-opens it or another div just like it, the last image shows (stays) when it shouldn't in the main div. Instead, it should be showing the first thumbnail img in the main div...
Any suggestions is appreciated and below is what I currently have (or at least a portion of it). There is a lot more, but below is the main stuff that's giving me troubles...
*update: The HTML part is within a div class called "t_1". I have 24 of these..."t_1", "t_2", "t_3" respectively. And within this class, I have what is posted below in all using the same div classes. The only difference is the folder names in the img tag.
So, when a user clicks on that thumbnail and that thumbnail image gets rewritten so that it can be displayed in the main div "t_main_screenshot", all is good...but then, if the user clicks out of the "t_1" etc. divs, and opens up another "t_2", that last image thumbnail that was clicked previously shows in the main div (t_main_screenshot) instead of the first image thumbnail for what should be in "t_2"...
Hopefully this is a bit better in clarity...It's kind of hard to explain.
HTML:
<div class="t_main_screenshot">
<img src="_framework/images/slides/simplicity/2.png" alt="" title="" />
</div>
<div class="t_thumbnail_wrapper">
<div class="t_thumbnail active">
<img src="_framework/images/slides/simplicity/2-thumbnail.png" alt="" title="" />
</div>
<div class="t_thumbnail">
<img src="_framework/images/slides/simplicity/4-thumbnail.png" alt="" title="" />
</div>
<div class="t_thumbnail">
<img src="_framework/images/slides/simplicity/6-thumbnail.png" alt="" title="" />
</div>
</div>
JS / JQuery:
$('.t_thumbnail').click(function() {
$('.t_thumbnail').removeClass('active');
$(this).addClass('active');
var thumbNail = $(this).find('img').attr('src');
$('.t_main_screenshot img').fadeOut(0, function() {
$(this).fadeIn().css('animation','scale-in .75s ease-in 0s forwards')[0].src = thumbNail.replace('-thumbnail', '');
});
});

Your question isn't clear, but I think you mean when the user clicks two times so quickly, you will see a flash...
That's because you're using .fadeOut() and .fadeIn()
So to fix this issue you can use .stop() method to stop the previous animation before starting the new one
More details: https://api.jquery.com/stop/
According to the question updates
Here is the problem: $('.t_main_screenshot img').fadeOut(0, function() {
You have to select the closest t_main_screenshot
Correct way:
$(this).closest('.t_thumbnail_wrapper')
.siblings('.t_main_screenshot')
.find('img').fadeOut(0
Let me know if this works...

$('.t_thumbnail').click(function() {
$('.t_thumbnail').removeClass('active');
$(this).addClass('active');
var thumbNail = $(this).find('img').attr('src');
var res = thumbNail.substring(1, thumbNail.indexOf("-"));
res+=".jpg";
$('.t_main_screenshot img').fadeOut(0, function() {
$(this).fadeIn().css('animation','scale-in .75s ease-in 0s forwards')[0].src = res;
});
});

Finally figured out the answer to this:
$('.t_thumbnail').click(function() {
$('.t_thumbnail').removeClass('active');
$(this).addClass('active');
var thumbNail = $(this).find('img').attr('src');
$(this).parent().parent().siblings().find('.t_main_screenshot').children('img').fadeOut(0, function() {
$(this).fadeIn().css('animation','scale-in .75s ease-in 0s forwards')[0].src = thumbNail.replace('-thumbnail', '');
});
});

Related

How to make an element appear then disappear on click

I have been trying to make a random image appear on click by adding a fadeOut effect and then removing the class. when I click it works fine, but I don't know how to remove the class after a few milliseconds and then being able to appear again on another click. so far I have just been able to make it fade out on click, I have tried a setInterval function so that the class gets removed after 1 millisecond but didn't work so I erased it, but even then, I don't know how to make the .on('click', function()) function fire on every click, instead of just working once. any help or tips would be really appreciated. Thanks!
<style>
body {
background-color: black;
}
img {
opacity: 0;
width: 40px;
z-index: 0;
position: relative;
top: 3em;
}
</style>
<img class="red"
src="http://www.clker.com/cliparts/0/f/1/f/130267960774173786paint-
splash(red)-md.png" alt="">
<img class="blue" src="http://www.clker.com/cliparts/Q/3/H/u/Z/K/dark-blue-
splash-ink-hi.png" alt="">
<img class="yellow" src="http://www.clker.com/cliparts/3/y/m/m/p/P/yellow-
splash-ink-md.png" alt="">
<script>
$(document).ready(function(){
var red = $(".red");
var blue = $(".blue");
var yellow = $(".yellow");
var images = [red, blue, yellow];
$(document).on('click', function(){
$(images[(Math.floor(Math.random()*3))]).addClass("animated fadeOut");
});
})
//i should be able to click anywhere on the screen and a random image should appear and then fadeout each time there is a click
</script>
Try something like this:
$(document).on("click", function() {
$("#element").show(0, function() {
$("#element").fadeOut();
});
});
$("#element").hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="element">Element</span>
It looks like you are using jQuery so you simply need to:
1) Create a function that hides the class. Example:
function hideStuff(){
$(".myimg").hide();
}
2) Add a class to your image files so they have a common selector (like "myimg" below). You may also want to add an "alt" attribute (was missing in your code). Example:
<img class="yellow myimg" src="http://www.clker.com/stuff" alt="image-three">
3) Add the timeout as part of your function with the amount of delay you want. While it is not required, you should include a variable name so you can call it in the future. Example:
var myTimeout = setTimeout( hideStuff, 5000);
Hopefully these will get you going in the right direction.
Both .fadeOut() and .hide() set display: none, which could effect your layout. I think you're looking to animate opacity to 0, and then in the callback function you can change the image source. I'd recommend using a div and setting the background-image property since divs are a bit more layout friendly. Also, you could either use classes and set the background-image property in the <style> section or you can make an array of the image urls and randomly pick from that (which is what I did here).
let images = [
'http://www.clker.com/cliparts/0/f/1/f/130267960774173786paint-splash(red)-md.png',
'http://www.clker.com/cliparts/Q/3/H/u/Z/K/dark-blue-splash-ink-hi.png',
'http://www.clker.com/cliparts/3/y/m/m/p/P/yellow-splash-ink-md.png'
];
$(document).on('click', function() {
let $img = $('.img'); //so you don't have to make a new object everytime it's used
if ($img.css('opacity') === '1') {
$img.animate({ opacity: 0 }, function() {
$img.css('background-image', `url(${images[Math.floor(Math.random()*3)]})`);
});
} else {
$img.animate({ opacity: 1 });
}
}).click().click(); //two clicks to initialize image
https://jsfiddle.net/yc4e4nxb/3/
NOTE: JSfiddle doesn't seem to like wherever these images are hosted, so it's working kind of erratically. Hopefully you get the gist of what this code is doing though.
http://api.jquery.com/animate/
If I understood the question correct, In This Fiddle the button element disappears when you click anywhere in the screen and then re appears immediately. Hope this will work.
$(document).ready(function(){
$(document).on('click',function(){
$("#myElement").fadeOut().delay(100).fadeIn();
});
});

Overlay overrules images - Can't automate src

I have an image that uses jquery for when an image is clicked, this will return the image src for that image. I modified my HTML/CSS to give this image an overlay.
However, I have now added an overlay that comes from left to right when the image is hovered. This added complications, as now when the jquery tries to find the image src, it can't because the overlay is covering it.
This has meant I have to manually write the code for each image src, but this does not work because obviously when you click each image, each one will have a different img src.
To provide example:
$(".dogs img").click(function(){
var src = $(this).attr("src");
});
Now that I have an overlay, unless I'm really fast and beat the overlay covering my screen, I can't click the image, but only the overlay covering it.
<div class = "cover-overlay">
<img src = "dog-1.png">
</div>
<div class = "cover-overlay">
<img src = "dog-2.png">
</div>
<div class = "cover-overlay">
<img src = "dog-3.png">
</div>
So now I have to do,
$(".dogs .cover-overlay").click(function(){
var src = $(".dogs img").attr("src");
}
however this will obviously always return the source of the first image in dog class, because of how the click function now works with overlay. Any suggestions?
You can still use this to reference the clicked .cover-overlay element, but now you need to also use find() to get the child img from it:
$(".dogs .cover-overlay").click(function(){
var src = $(this).find('img').prop("src");
});

change background image in no time

I am changing background image of a div on event basis,
There are two image
Image1
and
Image2
I have to use these two images on condition basis, it is working fine, but at first time when i change image, it takes time to load, how to load it instantly
div has image1 as default background image,
and I am changing it with below code
$("div").addClass('loadalternateImage');
alternate image is class with background-image with image2
but it take time to load Image2.
Please advise how to load it instantly
Thanks
You can preload both images in a div outside the viewport. So, when you click in order to change background, both images should have been loaded.
HTML:
<div class="img-container">
<img src="first/img" />
<img src="second/img" />
</div>
CSS:
.img-container {
position: fixed;
top: -100000px;
}
You can also bind the click event after page loads (not on document ready) in order for the images to get fully loaded:
$(window).load(function() {
$(document).on('click', '#your-div', function() {
// change background
});
});
Option 1
I suggest you to have a look at this post
Therefore, you could use the base64 encoding for your image and put it directly to your stylesheet:
loadalternateImage {
background: url(data:image/gif;base64,....) no-repeat left center;
}
Option 2
Alternatively, you could put this your into some invisible node, which would also trigger the preloading:
<img src="original.jpg">
<img src="secondary.jpg" style="display:none;">
Option 3
Use sprites - have a look at this post. It is the most difficult solution from the maintenance point of view
Ok retain the answer by #kapantzak but do this
Switch between
$("#imgBackground')[0].src = $("#firstImg")[0].src
and
$("#imgBackground')[0].src = $("#secondImg")[0].src
imgBackground is the id of IMG tag as your background.
//Code block from #kapantzak
$(window).load(function() {
$(document).on('click', '#your-div', function() {
// put the code above here..
});
});

Image caption coming in before image has fully faded in

I have a gallery where I use the 'alt' as it's caption and I got it to perform correctly when calling the image, displaying image with the caption z-index'd above it but for some reason the caption is coming in too early (i noticed this because if i keep clicking the same image, everything fades in except the actual caption text).
I have all the css already provided and have created a div with append, actually it's probably easiest to just show the code
Here is the code:
function gallery(){
$('#gallery a').click(function(evt){
evt.preventDefault();
oldImage = $('#thumbs').next();
var imgPath = $(this).attr('href');
var newImage = $('<img class="galleryBig" src="' + imgPath + '">');
//get nextCaption information for each click(only applies to anchors)
var nextCaption = $(this).find('img').attr('alt');
newImage.hide();
$('#thumbs').after(newImage);
//displays caption for each image and replaces old caption (if applicable)
$('div.caption').replaceWith('<div class="caption">' + nextCaption + '</div>');
newImage.fadeIn();
oldImage.remove();
}); //end anonymous fcn
} //end gallery
I am completely stumped on how to get the caption to work with the image as if they were both one item (fade in fade out with eachother)
There's an easy workaround for this:
You could just use the following method which will allow you to fadeIn() the image and once the fadeIn has finished, then load the caption.
Here is the code:
$('.imageToFadeIn').fadeIn(800, function(){
//load here the caption
})
what the above code will do is that once the fadeIn() function is finished, it will perform the next function where you can load your caption.
Read the documentation for a better understanding of what the function after the duration does.
http://api.jquery.com/fadeIn/
If you want both to load at the same time, then get both elements, the picture and the caption into a div and then fadeIn() the div instead like this:
html:
<div class="pictureAndCaption">
<img src="source">
<span>Caption text</span>
</div>
jQuery:
$('.pictureAndCaption').fadeIn(800);

Large images prevent div from fading in

I've got this setup:
<div id="container1">
<!-- content from one section -->
</div>
<div id="container2" style="display:none;">
<div id="sub-container">
<img src="image1.png" />
<img src="image2.png" />
<!-- 20 or so images sit here -->
</div>
</div>
container1 is initially displayed. On document.ready, all but the first four images are hidden away in order to build a carousel of sorts.
The user clicks a button, container1 fades out and container2 fades in.
The first time the user clicks the button, container2 doesn't fade in, instead it jumps straight to visible. The second time, fade in works as normal.
The images involved are pretty substantial (~10MB total size) but that hasn't been an issue so far as the page is meant to be viewed locally. The fact that the issue doesn't appear if I've got one or two images tells me the browser is struggling to both load the images and fade in at the same time. The second time it loads, the images have been cached and fade in as normal.
I tried a form of preloading like so:
/* take the div outside the viewport but still render it */
.hide {
position: absolute;
top: -9999px;
left: -9999px;
}
var cacheContainer = "<div class='hide'></div>",
$images = $("#sub-container img");
// move the images to the container
$(cacheContainer).appendTo("body").append($images);
// hopefully 500ms would be enough for the images to render?
setTimeout(function () {
images.appendTo("#sub-container");
doGallery(); // build carousel
},500);
... this however leads to the same issue - container2 pops in instead of fading the first time round, and works perfectly fine afterwards.
Any ideas?
As requested, here's what I use to hide/show the containers:
$(document).ready(function() {
var $currentTab = $("#container1"),
$newTab,
newTabName;
// a couple of more unrelated setting up functions go here
doImageCaching(); // the function I've got above
$("#container2").hide();
$("#tab-links>a").click(function(e) {
e.preventDefault();
// probably a bit cheeky doing it this way but oh well
newTabName = $(this).attr("id").replace("-btn", "");
if($currentTab.attr("id") === newTabName) {
return;
}
$newTab = $("#" + newTabName);
$newTab.stop(true, true).fadeToggle(200);
$currentTab.stop(true, true).delay(100).fadeToggle(200);
$currentTab = $newTab;
$newTab = null;
});
});
Here's #tab-links for reference:
<div id="tab-links">
<a id="container1-btn" href="#">show container 1</a>
<a id="container2-btn" href="#">show container 2</a>
</div>
Edit 2 So I just noticed something new: so the second time I switch to container2 it fades in as normal. If I wait 10 seconds or so, and then try and switch to container2 again, the problem reappears.
So it seems to me loading the DOM has nothing to do with this, and I'm dealing with Chrome's internal memory. So it loads the images, and then "forgets" about them when they hide again. Yikes.
Does anyone have any ideas as to how to keep the browser from "forgetting" the images, or is that a direction I shouldn't really take?
So I ended up converting my ultra-high quality PNGs to ultra-high quality JPGs - this led to an approximately 20-30% reduction in file size with barely any reduction in apparent quality. My problem disappeared, too.
The moral of the story is: even if you're developing a page that isn't going online, you still need to optimize your images.
Thank you all for your help.

Categories