querySelectorAll is not working with data-srcset - javascript

I want to apply a class to all the horizontal imgs on the website.
I'm trying to use this function below but it doesn't work.
Any help would be greatly appreciated.
$(function() {
var images = document.querySelectorAll('[data-srcset]');
for (var i = 0; i < images.length; i++) {
if (images[i].naturalWidth > images[i].naturalHeight) {
$(images[i]).addClass('horizontal');
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-srcset="https://cdn.pixabay.com/photo/2015/02/18/11/50/mountain-landscape-640617_960_720.jpg" alt=landscape>

That is because the data:... image you provide is 1x1 and so the check for images[i].naturalWidth > images[i].naturalHeight fails.
Keep in mind that if you use the srcset attribute (instead of data-srcset) which is the default it will work as expected (but you need to use the load event of the page).
$(window).load(function() {
var images = document.querySelectorAll('[srcset]');
for (var i = 0; i < images.length; i++) {
if (images[i].naturalWidth > images[i].naturalHeight) {
$(images[i]).addClass('horizontal');
}
}
})
.horizontal{border:10px solid OliveDrab;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" srcset="http://www.dummyimage.com/400x200" alt=landscape>
<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" srcset="http://www.dummyimage.com/200x210" alt=landscape>

It's better to replace alt=landscape with alt="landscape".
both
var images = document.querySelectorAll('[data-srcset]');
and
var images = $('[data-srcset]');
works for me.
Your problem is if statement is not true. it's always go to else.
Try update your if statement by the following code.
if (images[i].naturalWidth > images[i].naturalHeight) {
$(images[i]).addClass('horizontal');
console.log(images[i]);
} else {
console.log('else');
}
You'll see that it's always go to else.

Related

using javascript in html to delete things when clicked

I have previously posted about this page Im trying to create and Im still running into errors. I am very new to this and getting confused. I need to use a for loop to loop over the images and assign an event listener to each one so that when they are clicked on they get deleted. Im getting confused with the difference variables and pulling the html into my javascript. I keep getting ".addEventListener is not a function" and so I keep changing things but getting lost.
<!DOCTYPE html>
<html>
<body>
<div id = 'img'>
<img src="https://www.sciencemag.org/sites/default/files/styles/article_main_large/public/dogs_16x9_0.jpg?itok=byPuhQjh" id="img"/>
<img src="https://www.yvr.ca/-/media/yvr/blog/2018/57_yvr_puppies_2018.jpg" id="img"/>
</div>
<script text="javascript">
let images = document.querySelectorAll("img");
for (let i = 0; i < images.length; i++){
images[i].addEventListener("click", () => {
images[i].remove();
});
}
</script>
</body>
</html>
You are accessing array directly, which won't have the addEventListener. Try images[i].addEventListener
images.addEventListener should be images[i].addEventListener. You want to add the listener to the specific image from the array, not the array itself. Similar problem with images.remove().
First, you have same id for your container and both of your images - ID is supposed to be unique.
Second, as people already mentioned, you can not attach eventListener to array of objects.
Something like this shoud do:
let images = document.querySelectorAll("[id^='img']");
for (let i = 0; i < images.length; i++){
images.forEach(i=>{i.addEventListener("click", () => {
i.remove();
});
});
}
<div id = 'box'>
<img src="https://www.sciencemag.org/sites/default/files/styles/article_main_large/public/dogs_16x9_0.jpg?itok=byPuhQjh" id="img1"/>
<img src="https://www.yvr.ca/-/media/yvr/blog/2018/57_yvr_puppies_2018.jpg" id="img2"/>
</div>
you cannot attach an event handler to a list of images
so loop over images and for each of them
// for each image in images
image.onclick = function (e) {
e.target.parentNode.removeChild(e.target);
This will help you - https://jsfiddle.net/n5mk9Lzj/
let images = document.querySelectorAll("img");
for (let i = 0; i < images.length; i++) {
images[i].addEventListener("click", function() {
images[i].remove();
});
}
You need to update your code, you are not using index inside loop.You cannot add any listener on directly to images array.
<!DOCTYPE html>
<html>
<body>
<div id = 'img'>
<img src="https://www.sciencemag.org/sites/default/files/styles/article_main_large/public/dogs_16x9_0.jpg?itok=byPuhQjh" id="img"/>
<img src="https://www.yvr.ca/-/media/yvr/blog/2018/57_yvr_puppies_2018.jpg" id="img"/>
</div>
<script text="javascript">
let images = document.querySelectorAll("img");
for (let i = 0; i < images.length; i++){
images[i].addEventListener("click", () => {
images[i].remove();
});
}
</script>
</body>
</html>

Javascript: Error in custom script for lazyload images

I am trying to write the following script to lazyload background images of sub-menu on a website. But this function returns the error
Missing ) after argument list
My requirement is to load the background images after the window loaded completely. What i am doing is , I have added some data attributes to get the background image url, position etc. and then on windows load call this function which adds the css for the sub-menu.
<script>
function menuImageLazyLoad() {
var imgDefer = document.getElementsByClassName('megamenu-content');
for (var i = 0; i < imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-background-image')) {
imgDefer[i].css(
"background-image":+imgDefer[i].getAttribute('data-background-image'),
"background-position":+imgDefer[i].getAttribute('data-background-position'),
"background-repeat":+imgDefer[i].getAttribute('data-background-repeat')
);
console.log(imgDefer[i].getAttribute('data-background-image'));
}
}
}
window.onload = menuImageLazyLoad;
</script>
console logs returns the url of image:
url(image/sub_menu_image.jpg)
How can i fix this problem?
Update:
This is the final solution for my problem. I hope it may help someone
<script>
function menuImageLazyLoad() {
var imgDefer = document.getElementsByClassName('megamenu-content');
for (var i = 0; i < imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-background-image')) {
$(imgDefer[i]).css("background-image",imgDefer[i].getAttribute('data-background-image'));
$(imgDefer[i]).css("background-position",imgDefer[i].getAttribute('data-background-position'));
$(imgDefer[i]).css("background-repeat",imgDefer[i].getAttribute('data-background-repeat'));
}
}
}
window.onload = menuImageLazyLoad;
</script>
I guess you miss {}
For multiple attribute css settings,
It should be set as an object https://www.w3schools.com/jquery/jquery_css.asp
imgDefer[i].css(
{"background-image":+imgDefer[i].getAttribute('data-background-image'),
"background-position":+imgDefer[i].getAttribute('data-background-position'),
"background-repeat":+imgDefer[i].getAttribute('data-background-repeat')
});

Javascript modification of CSS class url change for background image

I am trying to get a background image to change based on a setting in the database, for right now I'm just trying to get a a way of simply modifying the image used without using the data base but I'm hitting a snag. Without the javascript the image appears fine, with the javascript it is simply not there; leading me to believe there is an issue finding the path written to the css.
Thanks in advance for any help!
<script type="text/javascript" language="javascript">
function changecss(myclass, element) {
var CSSRules
var link1 = "url('../../graphics/MainMenuBG0.gif')";
var link2 = "url('../../graphics/MainMenuBG1.gif')";
if (document.all) {
CSSRules = 'rules';
}
else if (document.getElementById) {
CSSRules = 'cssRules';
}
for (var i = 0; i < document.styleSheets[0][CSSRules].length; i++) {
if (document.styleSheets[0][CSSRules][i].selectorText == myclass) {
if (document.styleSheets[0][CSSRules][i].style[element] == link1) {
document.styleSheets[0][CSSRules][i].style[element] = link2;
} else {
document.styleSheets[0][CSSRules][i].style[element] = link1;
}
}
}
}
</script>
You should try something like this :
if (document.styleSheets[0][CSSRules][i].style.getProperty('background-image') == link1) {
document.styleSheets[0][CSSRules][i].style.setProperty('background-image', link2);
} else {
document.styleSheets[0][CSSRules][i].style.setProperty('background-image', link1);
}

Image-loaded-show function by javascript in mobile browser

I'am using the following javascript code to implement image-loaded-show function in mobile web browser (supporting HTML5). Image-loaded-show means that before the image is completely loaded, the width and height is 0, namely it willn't show and occupy any space.
Now the problem is that the images will not show until all the images are loaded.
What I need is that the iamge in the page is seperate, once loaded, the image show up.
Any tips on how to modify this javascript code? thanks.
<script type='text/javascript'>
var srcs = [];
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
}
var content = document.getElementById('content');
var images = content.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
srcs[i] = images[i].src;
loadImage(images[i], srcs[i],
function (cur, img, cached) {
cur.src = img.src;},
function (cur, img) {
cur.style.display = 'none';});
}
};
var loadImage = function (cur, url, callback, onerror) {
var img = new Image();
img.src = url;
img.width = '100%';
if (img.complete) {
callback && callback(cur, img, true);
return;
}
img.onload = function () {
callback && callback(cur, img, true);
return;
};
if (typeof onerror == 'function') {
img.onerror = function () {
onerror && onerror(cur, img);
}
}
};
</script>
The source code of the page is :
<body onload="doBindLinks();"><div id="content"> images and text </div></body>
P.S: Because I need to write this javascript string in C#, I replace the (") into (').
Edited:
Is the following right:
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
elem.setAttribute('display','none');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
elem.attachEvent('onload',onImageLoaded);
}
};
window.onImageLoaded = function() {
var elem = event.srcElement;
if ( elem != null ) {
elem.setAttribute('display','block');
}
return false;
};
Besides, the css code is:
img {width: 100%; border-style:none;text-align:center;}
But the images still wouldn't show until all are loaded.
I'm not 100% sure I understand your question. Are you trying to hide the image until it is fully loaded? Are you writing the images out to the page, or are they already in the page? Here are a couple of options:
set style="display:none". Then add onload="this.style.display='';" event listener to image.
images will each show as they are loaded.
if you are able to change the c# code, then simply write all the image urls out as a list of strings into an imageload function. Then use this function to create the images and add them to the content div.
I hope this helps you. If not, please provide more context, and I will try to help farther.
Ok, I see where you are going now. You can take out all that javascript that you have written. Maybe print it out so that you can throw it in the trash. Then take my example here... and it will do the trick for you. each image shown only as it is loaded. Obviously if you want to change any other properties you can do it in the showImage function. hope this helps.
<html>
<head>
<style>
img{display:none;}
</style>
<script type="text/javascript">
function showImage(elem) {
elem.style.display = 'block';
}
</script>
</head>
<body><div id="content">
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
</dvi>
</body>
</html>

How to hide all images using javascript?

I'm injecting JavaScript code into a website for personal use, using a Google Chrome extension... I'd like to hide all images before the page loads... I've got the script to run before anything loads, but can't seem to get the correct code to hide the array of images... something like:
function beforeload(){
document.getElementsByTagName('img')[0].style.display = "none"
}
Basically i want all the image tags to have style="display:none" added to the attributes. how do i do this?
You need to loop on them
var images = document.getElementsByTagName('img');
for (i = 0; i < images.length;i++ ) {
images[i].style.display = "none";
}
Amr has got the way to do it with javascript. If you add jquery to the page, it only takes one line
$('img').hide();
Below code will only hide images of all image elements
let images = document.getElementsByTagName("img");
let images_length = images.length;
for (let i = 0; i < images_length; i++) {
images[i].style.setProperty("display", "none", "important");
}
but what if images are displayed using CSS ?
Solution for all elements
let images = document.getElementsByTagName("img");
let images_length = images.length;
for (let i = 0; i < images_length; i++) {
images[i].style.setProperty("display", "none", "important");
}
/** now also hide images which are implemented in css */
let all_elements = document.querySelectorAll("*");
for(let i = 0 ; i < all_elements.length ; i++){
all_elements[i].style.setProperty("background-image","unset","important");
}
.image {
width : 100px;
height : 100px;
background-image : url(https://image.shutterstock.com/image-photo/aerial-view-main-faisal-mosque-600w-1242735640.jpg);
}
<img src="https://image.shutterstock.com/image-photo/aerial-view-main-faisal-mosque-600w-1242735640.jpg" width="100" height="100">
<div class="image"></div>
<div> To show images plz comment/remove js </div>
Check this out:
http://ncthakur.itgo.com/js09.htm
It's not exactly what are you looking for, but you can use some part of it.
It took me 7 seconds to find it on google ;)

Categories

Resources