Preload image on event - javascript

How can I preload image only when event starts, i.e. .scroll or .click ?
What happens now is, image loads along with website, and I want to prevent this from happening.
Thanks.

Use .one() , .appendTo()
$(element).one("click", function() {
$("<img src=/path/to/img/>").appendTo(/* target element */)
})
$(window).one("scroll", function() {
$("<img src=/path/to/img/>").appendTo(/* target element */)
})

Maybe something like this:
$(function() {
$('img').each(function() {
var self = $(this);
self.attr('data-src', self.attr('src'));
self.removeAttr('src');
});
var loaded = false;
function loadImages() {
if (!loaded) {
$('img').each(function() {
var self = $(this);
self.attr('src', self.data('src'));
});
loaded = true;
}
}
$('button').click(loadImages);
$(window).scroll(function() {
loadImages();
$(this).unbind('scroll');
});
});
if the javascript is executed after images are loaded you can try to change img src to data-src in html file.

You could create an image tag with the source in an data attribute:
<img data-src="your_image.jpg">
And then load it on an event:
$('body').on('click', function(){
$('img[data-src]').each(function(i, img){
$img = $(img);
$img.attr('src', $img.data('src'));
$img.removeAttr('data-src');
});
});

This should work
$(function(){
$(document).one("scroll, click", function(){
loadImages();
})
})
Here loadImage is a function which will load your images on click/scroll event. "one" method will make sure that it only happens only once else you will end up loading images every time someone click or scroll.

var src = 'location/file.jpg';
$(document).on('click', function(){
$('target').append('<img src="' +src+ '" />');
});

Related

stopPropagation not working in jquery

I have a list of images, list contains a JPG image, on mouseover image is replaced with a GIF animation, and some text is displayed above image.
Issue is that text is firing mouseover / mouseout events. I tried to add stopPropagation() function, but its now working.
What else can be done, or am i doing something wrong?
JSFiddle: https://jsfiddle.net/alokjain_lucky/8f2gqua4/
HTML Code:
<ul class="images-list">
<li data-gif="https://res.cloudinary.com/hu0zdcb0k/image/upload/fl_lossy,q_25/rbgo5mkmu0dldrtobrwg.gif" data-jpg="https://res.cloudinary.com/hu0zdcb0k/image/upload/w_180,h_180,q_55,c_fill,g_face,e_improve/vt5yhnzexh3vqa89hbtz.jpg">
<a href="https://www.picnic.lol/qrVy4yA">
<img src="https://res.cloudinary.com/hu0zdcb0k/image/upload/w_180,h_180,q_55,c_fill,g_face,e_improve/vt5yhnzexh3vqa89hbtz.jpg" alt="" width="167" height="168">
</a>
<span class="image_caption">Some text here</span>
JS Code:
$(document).ready(function() {
$('.images-list li').on('mouseover', function(e) {
e.stopPropagation();
var self = $(this);
self.find('.image_caption').stop().fadeIn('slow');
var image = new Image();
image.src = $(this).data('gif');
image.onload = function() {
self.find('img').attr('src', image.src);
}
image.onerror = function() {
console.error("Cannot load image");
}
})
$('.images-list li').on('mouseleave', function(e) {
e.stopPropagation();
$(this).find('img').attr('src', $(this).data('jpg'));
$(this).find('.image_caption').stop().fadeOut('slow');
});
})
stopPropagation isn't going to help because it only stops the same event from propagating to other elements. Your case is firing a separate time. You need to use mouseenter instead of mouseover.
$(document).ready(function() {
$('.images-list li').on('mouseenter', function(e) {
var self = $(this);
self.find('.image_caption').stop().fadeIn('slow');
var image = new Image();
image.src = $(this).data('gif');
image.onload = function() {
self.find('img').attr('src', image.src);
}
image.onerror = function() {
console.error("Cannot load image");
}
})
$('.images-list li').on('mouseleave', function(e) {
e.stopPropagation();
$(this).find('img').attr('src', $(this).data('jpg'));
$(this).find('.image_caption').stop().fadeOut('slow');
});
})
Use mouseenter (MDN) instead of mouseover (MDN).

jquery swap image on element click not functioning

I am trying to swap an image on click with jquery. I have got it to work with the click being bound to the image class. However, if I try and wrap the function and bind the event to a button or anchor, it will not swap the images. Here is the jquery:
<script type="text/javascript">
jQuery(document).ready(function( $ ) {
$(".test_toggle").click(function(){
$(this).find(".img-swap").live('click', function() {
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});
});
</script>
This worked:
jQuery(document).ready(function( $ ) {
$(".img-swap").live('click', function() {
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});
Any help is greatly appreciated.
I don't think there's any need to delegate the event listeners so I've removed them. Simply add the click event to the image and then you can manually 'trigger' a click on it when the .test-toggle is clicked. E.G:
$(function() {
//add on click event
$(".img-swap").on('click', function() {
if (this.src.indexOf("_off")>0) {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
});
//add remote trigger
$(".test_toggle").on('click', function(){
$(".img-swap").trigger("click");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="img-swap" src="https://placehold.it/300?text=_off" />
<button class="test_toggle">test toggle</button>
Thats because unlike like img.
a or button doesn't have a src attribute.
So when you bind the event to a button or anchor, this.src in your second instance of the code will be invalid.
I would delete this line:
$(this).find(".img-swap").live('click', function() {
What is it's purpose? You can swap this image right after the first click, right?
Also, make sure that .img-swap is inside the tag with class test_toggle.
You are using:
$(this).find(".img-swap")
find() searches only in children of selected element.
If it's not nested use
$(".img-swap")
instead of:
$(this).find(".img-swap")
I have re-written the js, but not tested. Can I nest clicks?
$(".test_toggle").click(function(){
$.find(".img-swap").click(function(){
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});

Why changing img src with jQuery works incorrectly?

Well, the task is to change img src on click.
It was not a problem to do it.
But I'd like to have some effect while changing it.
So, I used fadeOut and fadeIn. Problem is when the img src is changing the img starts "sparkling / blinking".
You can see an example here
http://www.coffee-cult.ru/slidersupreme
(rectangle in top right corner activates slider buttons)
and the code,
$main_image = $("img").first();
$("#prev_slide").click(function(e) {
e.preventDefault();
$main_image.fadeOut(400, function() {
$main_image.attr('src', images[0]);
}).fadeIn(400);
});
$("#next_slide").click(function(e) {
e.preventDefault();
$main_image.fadeOut(400, function() {
$main_image.attr('src', images[1]);
}).fadeIn(400);
});
you can try to use
$(this).attr();
instead of
$main_image.attr();
It has something to do with your other scripts on the page. Here in the fiddle it looks kind of alright with the same code: http://jsfiddle.net/ewyLcm0s/
var images = ['http://lorempixel.com/100/100/people/1','http://lorempixel.com/100/100/people/2'],
$main_image = $("img").first();
$("#prev_slide").click(function(e) {
e.preventDefault();
$main_image.fadeOut(400, function() {
$(this).attr('src', images[0]).fadeIn(400);
});
});
$("#next_slide").click(function(e) {
e.preventDefault();
$main_image.fadeOut(400, function() {
$(this).attr('src', images[1]).fadeIn(400);
});
});

JS change src on all images

I have a site, where I need to get all the images for eu.site.com, but the images are on us.site.com.
I would like to replace source on all of the images. Current function, that does not work:
$('img').each(function () {
var src = $(this).attr('src');
$(this).attr('src', src.replace(/_eu(\.[^.]+)?$/, '_us$1');
});
try something like this
$('img').each(function () {
this.src = this.src.replace("eu.site.com", "us.site.com");
});

How to display image src before href in jQuery

Have this block:
jQuery(document).ready(function($) {
$("img[src$='.jpeg'], img[src$='.jpg'], img[src$='.png'], img[src$='.gif']").wrap('<div class="b-img"/>').each(function() {
var src = $(this).attr('src');
var a = $('<a/>').attr('href', src).addClass('img-link').colorbox();
$(this).wrap(a);
});
})(jQuery);
and after that have link like <img src>... but I need <img src> before <a href="">
You can use after() instead of wrap
jQuery(document).ready(function($) {
$("img[src$='.jpeg'], img[src$='.jpg'], img[src$='.png'], img[src$='.gif']").wrap('<div class="b-img"/>').each(function() {
var src = $(this).attr('src');
var a = $('<a/>').attr('href', src).addClass('img-link').colorbox();
$(this).after(a);
});
})(jQuery);
Edit based on comments by OP, for changing image src
jQuery(document).ready(function($) {
$("img[src$='.jpeg'], img[src$='.jpg'], img[src$='.png'], img[src$='.gif']").wrap('<div class="b-img"/>').each(function() {
var src = $(this).attr('src');
var a = $('<a/>').attr('href', src).addClass('img-link').colorbox();
$(this).after(a);
$(this).attr('src', 'http://www.yoursite.com/images/img1.jpg');
});
})(jQuery);
insertBefore() inserts the elements before this, like so:
$(function() {
$("img").wrap('<div class="b-img"/>').each(function() {
$('<a />', {href: this.src, 'class': 'img-link'}).colorbox().insertBefore(this);
});​
});​
Also, there should be no need to check for all available image file extensions, if you have images that are svg etc, use a class instead.

Categories