OnMouseover image I am getting from custom meta box and OnMouseout image is featured image.
Here is my code:
$image_full = wp_get_attachment_image_src(get_post_thumbnail_id($postid), 'full');
$him = $post_meta['_hover_image'];
<img onmouseover="this.src=\'' .$him[0]. '\'"
onmouseout="this.src=\''.$image_full[0].'\'" src="'.$image_full[0].'" />
Everything is working fine but taking time to show image.
This issue is likely caused by the delay in loading the resource. To help with this, you can cache the image at the URL by loading it in JavaScript with something like the following:
function preloadImage(url)
{
var img=new Image();
img.src=url;
}
preloadImage($him[0]);
preloadImage($image_full[0]);
If the images are not dynamic, you can also preload them using CSS. More info about this can be found here: CSS3 image preloading
Related
UPDATE:
I just found some more info. It seems that in Chrome, the currentSrc of the image will often be empty, whereas in Firefox, the URL is always correct. Is the JS trying to access currentSrc before it's available? Is there a way to prevent this?
I am creating a Drupal 8 website, and in order to use the responsive images module with a background-image, I came up with the following workaround. The JS function below, setParallaxImage(), takes the currentSrc from the img in the picture element and sets it as the background-image for the outermost div. The img itself is not displayed (display: none in CSS) and is given a dummy image, as I only need it to get the currentSrc. The function is called with onload and onresize.
The code seems to work well in Firefox. When resizing the browser past a breakpoint, the image goes grey for a split second, then loads the image from the proper source. However, with Chrome, when quickly resizing past a breakpoint, the image may become grey and not get displayed at all, that is, background-image: url(). Usually if I resize the window a couple more times, the image will finally appear. Does anyone know why this might be happening? Thank you for reading.
JS
function setParallaxImage() {
const parallaxContainer = document.getElementsByClassName('paragraph--type--parallax-banner-with-text');
for(var i = 0; i < parallaxContainer.length; i++) {
console.log('in setparallax');
var x = parallaxContainer[i];
var parallax = x.getElementsByClassName('field--name-field-parallax-image-top-')[0];
var picture = parallax.getElementsByTagName("picture")[0];
var sourceURL = picture.querySelector('img').currentSrc;
x.setAttribute('style', 'background-image: url(' + sourceURL +')');
var img = picture.getElementsByTagName("img")[0].setAttribute('src', '/sites/default/files/src_images/dummy_image.gif');
}
}
window.onload = setParallaxImage
window.onresize = setParallaxImage;
HTML
<div class='paragraph--type--parallax-banner-with-text'>
<div class='field--name-field-parallax-image-top-'>
<picture>
<!-- several source tags here -->
<img src="will-be-given-dummy-image-in-JS">
</picture>
</div>
</div>
You can use the property "complete" to check, if the image was already loaded. If not, u can use the onload-Event to fire, when the image is available.
if (img.complete) {
console.log(img.currentSrc);
} else {
img.onload = function() {
console.log(img.currentSrc);
}
}
I've researched quite a bit and can't solve this issue. Only appears on Safari (Mac & iOS). Works on Chrome, FF, Edge, etc.
UPDATE: The flickering occurs in FireFox as well...
I'm using the IntersectionObserver API along with the required polyfil to lazy load images. When they come into view, the intersection observer replaces the low resolution image set as the background-image and replaces it with the high resolution image stored in a data attribute on the div.
The behaviour is 'working' as the blurry initial image is set, then replaced by the high quality one but there is a white flicker or flash happening inbetween... (The background of the page is white so maybe that's what is showing through?)
After some reading: (How to prevent a background image flickering on change) I did fix the jumping issue by preloading the images using the new Image() consructor.
const setBackgroundImage = (e) => {
let image = new Image();
image.onload = () => e.style.backgroundImage = `url(${e.dataset.bgImage})`;
image.src = e.dataset.bgImage;
};
An example HTML element (PHP):
<div class="my-div"
style="background-image: url('<?= $imagePreload ?? $image; ?>');"
data-bg-image="<?= $image; ?>"
</div>
I've tried playing around with backface-visibility: hidden but no luck there. I'm not animating anything, just replacing the src on the div with the preloaded, full size image.
You can solve this by loading the higher resolution image before it scrolls into view. Set the rootMargin option to something like 200px when creating your IntersectionObserver to have the browser start loading the image 200px before it enters the viewport.
I have a large gif animation on a web page and want to start it not until it's completely finished loading. How would that be possible using JavaScript / jQuery?
Use a placeholder image, and replace it with the animated GIF once that GIF is fully loaded:
<img id="anim" src="placeholder.gif">
JS:
var myanim = new Image();
myanim.src = '/img/actions.png';
myanim.onload = function() {
document.getElementById('anim').src = myanim.src;
}
http://jsfiddle.net/mblase75/6XTg7/
You can hide GIFs with CSS (or JS replacing them with a placeholder) and when GIFs are loaded you can fire show()
$('img[src$=".gif"]').load(function(){$(this).show())
You could hide it until it is fully loaded.
<!--- this uses jquery !-->
<script type="text/javascript">
var image_url = "http://media.tumblr.com/tumblr_m4doax3R071r9c1z7.gif";
var image = $('<img />').load(function(){
$(this).show();
}).attr('src', image_url).hide();
$('body').append(image);
</script>
The issue here is that once the image has been downloaded (i.e it is in the browsers cache), there really doesn't seem to be any way of starting it from a particular frame.
You have no control over gif animation through javascript, so you have to implement some sort of a hack. You have to make it hidden in the beginning. Instead of the actual picture you can put a div with the dimensions of the actual picture and with text like "wait".
When the image is downloaded in the browser you can substitute div with an image. And at that point of time animation will start
I have a problem with a mouseover script. Everything works as it should but I have a small issue that I don't know how to solve. More precisely, the mouseover script creates a grayscale image hover effect. When the page loads the colored images are showing for a short time (1 second or less) and then the javascript is applied and they are all grayed out which is exactly how things should work.
How can I make it so that the colored images will not appear before the javascript is applied? Basically, I want the grayscale images to appear when the page loads not after. Is it possible?
You can see the script here and the webpage in question here.
I would remove the images from the HTML and load them dynamically.
I would use <a class="placeholder" href=""></a> as placeholders for the <img src="" /> and would style the links to either be hidden or go well with the design.
$('a.placeholder').each(function() {
var src = $(this).attr('href');
var image = new Image(); // this is not yet visible in the DOM.
image.onload = grayscale; // change the grayscale function to accept
// event parameters
image.src = src; // this triggers the onload event which
// grayscales the image
var dom_image = $('<img />').attr('src', src);
$(this).replaceWith(dom_image);
});
Of course you have to be doing the above on document ready not on window load.
I noticed that when I do something like this (with jQuery, but I don't think it matters):
$("#myDiv").html("<img src='/image.png'/> this is my image.");
The browser displays the text first, and then the image is loaded, and shifts the text to the right which creates a horrible flickering effect.
The image doesn't appear to be cached by the browser. Any idea why ? How can I avoid this phenomena when loading images into the DOM ?
How can I avoid this phenomena when loading images into the DOM ? there are two major methods (may be more :))
1) Set the actual size of the img <img with='20' height='20' src='...' /> or via CSS style.
2) Use image preload and insert your code only when image is loaded
var img = new Image();
$(img).load(function(){
$("#myDiv").append($(this))
.append(document.createTextNode("this is my image.");
// or your way, browser should take image from cache
$("#myDiv").append("<img src='/image.png'/> this is my image.");
}).attr('src', '/image.png');
ps: there is a serious bag in SO engine - code formatting does not want to combine with numbered listing. So I removed the list.
Preload the image before attaching it:
$("<img>", {
load: function() {
$("#myDiv").empty().append( this, "this is my image." );
},
src: "/image.png"
});
preload your images like this
var images = [
'/path/to/some/image1.png',
'/path/to/some/image2.png'
];
$(images).each(function() {
var image = $('<img />').attr('src', this);
});
Images may render a little slower that text, even if cached. If you know the dimensions of the image add height and width attributes to the image and then it won't jump around.