Conditionally add class to image by jquery - javascript

This JS replace image file name default.jpg to hqdefault.jpg from all images below. But now I'm trying to add class to Image, if Image src has img.youtube.com link on images by extending this JS.
JS:
$('#selector img').attr('src',function(i,e){
return $(this).attr('src').replace("default.jpg","hqdefault.jpg");
});
HTML:
<div id="selector">
<img src="http://img.youtube.com/vi/qDc_5zpBj7s/default.jpg">
<img src="http://img.youtube.com/vi/ss7EJ-PW2Uk/default.jpg">
<img src="http://img.youtube.com/vi/ktd4_rCHTNI/default.jpg">
<img src="http://img.youtube.com/vi/0GTXMEPDpps/default.jpg">
</div>
Means, If image src has Youtube image then add a class .video to parent image.

Try:
$('#selector img').each(function(i) {
var self = $(this);
var src = self.attr('src');
if (src.match(/img.youtube.com/)) {
self.attr('src', src.replace("/default.jpg","/hqdefault.jpg"));
self.addClass('video');
}
});

You can add a condition before replacing and add video class.
$('#selector img').attr('src',function(i,e){
if($(this).attr('src').search('img.youtube.com') > 0){
$(this).addClass('video');
}
return $(this).attr('src').replace("default.jpg","hqdefault.jpg");
});

Related

Removing a folder from multiple img src tags with JS

I have a site with many different gallery categories that display a smaller thumbnail size until the screen width is below 1200px, after which I would like to display the full size instead.
The images are displayed like so:
<section class="gallery category1">
<img id="cat1img1" src="cat1/small/img-1.jpg" alt="blah">
<img id="cat1img2" src="cat1/small/img-2.jpg" alt="blah">
etc...
</section>
<section class="gallery category2">
<img id="cat2img1" src="cat2/small/img-1.jpg" alt="blah">
<img id="cat2img2" src="cat2/small/img-2.jpg" alt="blah">
etc...
</section>
And all I want to do is use a JS media query with some jQuery to remove the "small/" from each tag without listing every single img so they can be freely added and removed without modifying the code again.
This is what I've tried but it's not changing the img url, though it does trigger my size change check:
function galleryBreak(x) {
if (x.matches) {
$('.gallery').children('img').attr('src').replace('/small','')
console.log('size change check');
};
};
var x=window.matchMedia('(max-width: 1200px)')
galleryBreak(x)
x.addListener(galleryBreak)
You have multiple (2) galleries and multiple images. You need to iterate over all images for all galleries. Something like this
function changeImagePaths(theGallery) {
var images = theGallery.querySelectorAll('img');
images.forEach( image => {
console.log('Path before: ', image.src)
image.src = image.src.replace('/small','')
console.log('Path AFTER: ', image.src)
});
};
var x=window.matchMedia('(max-width: 1200px)')
var myGalleries = document.querySelectorAll('.gallery')
myGalleries.forEach( gallery => {
if(x.matches) {
changeImagePaths(gallery)
}
});
<section class="gallery category1">
<img id="img1" src="cat1/small/img-1.jpg" alt="blah">
<img id="img2" src="cat1/small/img-2.jpg" alt="blah">
</section>
<section class="gallery category2">
<img id="img1" src="cat2/small/img-1.jpg" alt="blah">
<img id="img2" src="cat2/small/img-2.jpg" alt="blah">
</section>
JsFiddle to play with here
Now all of that said, if you can change the HTML please use Responsive images which will show you all you need can be set right in the image tag like:
<img srcset="elva-fairy-320w.jpg,
elva-fairy-480w.jpg 1.5x,
elva-fairy-640w.jpg 2x"
src="elva-fairy-640w.jpg"
alt="Elva dressed as a fairy">
add resize event listener on window so that on each window / browser resize this event will be fired
const galleryBreak = () => {
if (window.matchMedia('(max-width: 1200px)').matches) {
const images = document.querySelectorAll('.gallery img');
Array.from(images).forEach(img => {
const imgSrc = img.src.replace('/small', '');
img.src = imgSrc;
console.log(imgSrc);
});
}
};
window.addEventListener('resize', galleryBreak);

Jquery Redirect to image src or data-attr

On a image inside link instead of use link href i would like to use img src to redirect to image path.
with this is possible to get the img src but how to use src to redirect? thank's
$(".drop a").click( function() {
alert($(this).children('img').attr('src'));
});
<div class="drop">
<a href""><img src=".." /></a>
</div>
Just use window.location
Code:-
$(".drop a").click( function() {
window.location = $(this).children('img').attr('src');
return false;
});

Onerror event add a new class and count how many times it replaces image source

I'm using onerror feature to detect broken links and replace those with an image, the problem is that in my code images that are okay are clickable.
So I want to make it in that way that when the function imageOnError is called to make that image impossible to click.
I tried to do it like this (img).unbind("click");
Lik this also: img.class = "blocked";
but it doesn't work?
<img class="img img-click not-selected " src="" onerror="return imageOnError(this);" />
countImgReplaced = 0;
function imageOnError(img) {
img.onerror = '';
img.src = 'https://dummyimage.com/256x256?text=Broken%20images%20.';
(img).unbind("click");
countImgReplaced ++;
return true;
}
And also I want to get the number of times that the image is replaced I did that with countImgReplaced , but it gives me the total number of images :/
I'm really confused. Can somebody help me?
You can apply pointer-events: none; to them via a class. You can apply that using the classList API
i.e.
img.classList.add('blocked');
You can just do this in HTML tag.
<img src="../resources/images/Image1.jpg" onerror="this.src='https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';this.style='pointer-events: none'" />
$(document).ready(function(){
$("img").click(function(){
alert("Valid");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="clear:both;"><lable>Click in image(Invalid img):</lable>
<img width=200px height=200px src="../resources/images/Image1.jpg" onerror="this.src='https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';this.style='pointer-events: none'" />
</div>
<div style="clear:both;"><lable>Click in image (Valid img):<lable>
<img width=200px height=200px src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQzltPjpuUfCzEsYbhTYTm4xab4wfmCTFoNllbU5ljLLEAb3VvJXkgpWvU" onerror="this.src='https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';this.style='pointer-events: none'" /></div>

Assign img' src dynamically

The page will display an image's url text correctly. But I am not sure how to assign the message to the img 's src to display the image.
<DIV class="msgStyle1" id="message">Waiting for image</DIV>
<div class="imgStyle1" id="message">
<img src=whatneedtogohere /></div>
function displayText(text) {
console.log(text);
document.getElementById("message").innerHTML=text;
window.castReceiverManager.setApplicationState(text);
};
Fixed HTML (switched classes and IDs to make IDs unique) and added an image ID for simplicity:
<div id="msgStyle1" class="message">Waiting for image</div>
<div id="imgStyle1" class="message">
<img src="" id="image" />
</div>
JS:
document.getElementById('image').src = 'http://yourImagePathHere';
See it work here: http://jsfiddle.net/N3rCm/
First off, you shouldn't have multiple Id's on the page, it'll mess with your JS.
Next I would give your image a class if you can
//jquery example of what you would do
var imgSrc = 'http://wherever/youre/getting/this/from';
$('.myimageclass').attr('src', imgSrc);
//non jquery
var myImg = document.getElementsByClassName('myimageclass')[0]; //assuming it's the first one
//or if you can uniquely identify it
var myImg = document.getElementById('imgId');
myImg.src = imgSrc;

Show "loading" while a new image is loading

I have
<img src="..." class="myImage">
<a href="..." class="changeImage">
$(function(){
$('a.changeImage').click(function(){
$('img.myImage').attr('src',NEWVALUE);
});
});
When I click the link, i inject a new src to .myImage. Is it possibile to show a loading image while the new src is loading?
Yes, you should use image preloading
var newImage = new Image();
var loadingSrc = 'loading.gif';
$('img.myImage').attr('src', loadingSrc);
newImage.onload = function() {
$('img.myImage').attr('src', newImage.src);
};
newImage.src = NEWVALUE;
$(function(){
$('a.changeImage').click(function(e){
e.preventDefault();
//show the loading div
$('img.myImage').attr('src',NEWVALUE);
$("img").trigger("onload");
});
$("img").bind("onload",function(){
//remove the loading div
});
});
http://jsfiddle.net/PrXSW/9/
You can use the load event (untested code)
<img src="smallLoader.png" alt="loading" id="loading" />
<img alt="bigImage" id="bigImage" style="display:none" />
<script type="text/javascript">
$(document).ready(function() {
$('#bigImage').load(function() {
$('#loading').hide();
$('#bigImage').show();
});
$('#bigImage').attr("src", "bigimage.png");
});
</script>
Take a look to the jquery.blockui plugin. It may fit your needing.
the simplest solution would be to declare the loading img via CSS as background-image.
#loaded-image {
/* shows loading icon until picture is fully loaded */
background-image: url(loading.gif);
background-repeat: no-repeat;
}

Categories

Resources