How to hide all images using javascript? - 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 ;)

Related

querySelectorAll is not working with data-srcset

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.

Can you generate html locally, without using a server?

I'm trying to show images in a local html file using a loop. This is what I want it to show in the web browser:
<div id="polybridges">
<img src="polybridge_1.gif">
<img src="polybridge_2.gif">
<img src="polybridge_3.gif">
<img src="polybridge_4.gif">
<img src="polybridge_5.gif">
</div>
This is my attempt to do this with javascript:
<script>
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
</script>
<div id="polybridges">
This doesn't generate anything. Is there a way to show images in a loop without using a server / localhost?
At first your element must be defined before script execution (so change the order). I suppose you want to append elem (instead of "hallo" string):
<div id="polybridges"></div>
<script>
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
</script>
Put your images in the same directory as your html file.
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
And change the argument for appendChild.
As malix states in his comment, you should use document.getElementById("polybridges").appendChild(elem); instead of document.getElementById("polybridges").appendChild("hallo"); (so append the element instead of string "hallo").
And, as the rest states, the images should be where you tell the browser they are.
Yes you can display images without server, you have to have that images in same directory as your html file or in images folder which in same level as your html file ( for that case images would be available as <img src="images/polybridge_5.gif">
appendChild take Node as parameter (not string)
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
You need to take care of one thing. You are trying to get element by ID. So you need to make sure that html is valid. Provide proper close tag for the element. Also use the elem variable in the appendChild().
for (var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src = 'polybridge_' + i + '.gif';
console.log(elem)
document.getElementById("polybridges").appendChild(elem);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="polybridges"></div>

Placing elements within a container div into an array - jQuery or JavaScript

I have a div that contains a number of Instagram images, produced by the instafeed.js plugin. After running the plugin, the resultant HTML looks like this:
<div id="instafeed">
<a><img /></a>
<a><img /></a>
<a><img /></a>
etc...
</div>
I am trying to find a way to load the contents of this div into an array; I believe that the easiest way would be to just take the tags, which is fine.
I'm pretty inexperienced with both JS and jQuery, which is why I'm having difficulty achieving this and I've not been able to find any forum posts that quite do what I'm hoping to achieve.
So far, all I'm trying to do is load the contents of the div into an array and print it back out to the document, which should (in my mind anyway) add the tags back into the HTML. I'm trying with both JavaScript and jQuery and having little success with either. I'd appreciate any thoughts:
JS:
var containerDiv = document.getElementById('instafeed');
var pics = containerDiv.getElementsByTagName('img');
console.log(pics); //Tells me at least that I have an array of img
for (var i = 0; i < pics.length; i++) {
document.write(pics[i]);
} //Seemingly does nothing
jQuery:
(I'm really sorry if this code is just all wrong, I really don't know jQuery very well at all)
$(document).ready(function() {
var pics = [];
$('#instafeed').find('img').each(function() {
pics.push($(this));
});
for (i = 0; i < pics.length; i++) {
console.log(pics[i]);
}
});
Any thoughts, tips or pointers would be much appreciated.
Edit:
Just to add a little background to my problem, to avoid causing any more confusion.
I'm trying to pull four random images from a user-specific Instagram feed for display on a website. instafeed.js can pull just four images and it can randomise the images, but Instagram itself always sends the four most recent images, so the plugin is just randomising the order of the same four pictures each time.
I'm trying to let the plugin send through every picture, which will go into the div instafeed. From here I want to load all of the contained images into an array so that I can randomly pick four images for display on the site.
JQuery code that you write is correct. Only you need the div where you need to put the images.
$(document).ready(function() {
var pics = [];
$('#instafeed').find('img').each(function() {
pics.push($(this));
});
for (i = 0; i < pics.length; i++) {
$('div#yourDiv').append(pics[i]);
}
});
See the line of the for()
You can extract only the SRC of the images and then make like you want
$('#instafeed').find('img').each(function() {
pics.push($(this).attr('src'));
});
console.log(pics); // returns an array of src.
Thank you to everyone who has tried to help me along with this. It turns out that the problem I was having stemmed from my query attempting to run before instafeed.js had been able to pull the images through from Instagram, and so there was nothing for it to find in the div. I've managed to fix this with a setTimeout.
For anyone who is interested, and just in case anyone else might come across this in future with a similar problem, here is my complete code (it's a little inelegant I'm sure, but I'm still a relative novice at JS.)
function snagImages() {
var pics = [];
$('div#instafeed').find('img').each(function() {
pics.push($(this).attr('src'));
});
reduceGallery(4, pics);
}
function reduceGallery(limit, pics) {
if (limit === undefined) {
limit = 4;
}
var gallery = [];
while (gallery.length < limit) {
var j = Math.floor(Math.random() * pics.length);
if ( gallery.indexOf(pics[j]) > -1) {
continue;
}
gallery.push(pics[j]);
}
displayPics(gallery);
}
function displayPics(gallery) {
for (var i = 0; i < gallery.length; i++) {
document.getElementById('gallery').innerHTML += '' + '<img src="' + gallery[i] + '" alt="Gallery Image" />' + '';
}
}
var userFeed = new Instafeed( {
options
});
userFeed.run();
setTimeout(function() { snagImages() }, 500);

Set css of multiple divs with same id

I have a reveal presentation in an iframe. Each slide has a div with an audio player in in and the divs id is "narration".
I have a button outside the frame that is used to hide/show this div. The problem is that it only does this for the first slide and not the rest.
EDIT : This seems to hide the divs :
function checkAudio() {
if (document.getElementById('cb1').checked) {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'none';
}
} else {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'block';
}
}
}
HTML in iframe (There is one for each slide) :
<div id="narration"><p align="middle">
<audio controls="" preload="none">
<source src="mp3/2.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio></p>
</div>
JS (outside of iframe):
function checkAudio() {
if (document.getElementById('cb1').checked) {
document.getElementById('ppt').contentWindow.document.getElementById('narration').style.display = 'none';
} else {
document.getElementById('ppt').contentWindow.document.getElementById('narration').style.display = 'block';
}
}
After changing your IDs to classes (read here why), you need to update your javascript code to handle the multiple divs via a foreach loop.
function checkAudio() {
var narrationDivs = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var newDisplay = "block";
if (document.getElementById('cb1').checked) {
newDisplay = "none";
}
narrationDivs.forEach(function(div) {
div.style.display = newDisplay;
});
}
In order to have the code run again when your iframe changes, you need to update your iframe changing function:
function setURL(url){
document.getElementById('ppt').src = url;
checkAudio(); // Just run the function again!
}
If you want to show a specific element using a button, you should use a specific ID. If you want to show all items using a single button you should use classes. You could also use classes to show a specific element e.g.: The 5th button will show the 5th element but this is not a good style.
When the site in the iframe loads the next frame, your code doesn't know to hide the div it presents again. You need an event to process on.
You need to poll the id so that if it shows up again, you can hide it. See: iframe contents change event?
function checkAudio() {
if (document.getElementById('cb1').checked) {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'none';
}
} else {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'block';
}
}
}
You might also want to check out the audio-slideshow plugin that allows to play separate audio files for each slide and fragment. If your main need is this, the plugin should do the job for you.
You can find a demo here and the plugin here. There is also the slideshow-recorder plugin that allows you to record your narration.
Asvin

How to populate alt fields with the src of an image for all images on page

I am working on a site that has a page that will have a couple hundred thumbnails. I would like to have the filenames (the src) of the images populate the alt fields. So for example, I currently have the thumbnails as follows:
<img src="images/thumb1.jpg" />
I would like to populate the alt fields with the filename. So, the desired result would be:
<img src="images/thumb1.jpg" alt="thumb1" />
Is there a way I can automatically generate these alt tags using the images src?
Any suggestions are appreciated. Thank you for the help!
An untested, first guess, would be:
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i=0; i<numImages; i++) {
images[i].alt = images[i].src;
}
JS Fiddle demo.
Just to demonstrate how much easier this can be, with a JavaScript library, I thought I'd also offer the jQuery demo too:
$('img').each(
function(){
this.alt = this.src;
this.title = this.src;
});
jQuery-based JS Fiddle demo.
Edited because I'm an idiot...
I forgot to point out that you'll need to wait for the window to finish loading (or, at least, for the document.ready event), so try it this way:
function makeAlt() {
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i = 0; i < numImages; i++) {
images[i].alt = images[i].src;
images[i].title = images[i].src;
}
}
And change the opening body tag to:
<body onload="makeAlt">
JS Fiddle demo.
Edited to address the OP's final question:
function makeAlt() {
var images = document.getElementsByTagName('img');
var numImages = images.length;
var newAlt, stopAt;
for (i = 0; i < numImages; i++) {
newAlt = images[i].src.split('/').pop();
stopAt = newAlt.indexOf('.');
newAlt = newAlt.substring(0,stopAt);
images[i].alt = newAlt;
images[i].title = newAlt;
}
}
JS Fiddle, though I suspect there's a far more concise way...
To get the file name you could add to David Thomas's code...
var name = images[i].getAttribute('alt').split('/');
name = name[name.length-1].split('.')[0];
So that you end up with...
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i=0; i<numImages; i++) {
var name = images[i].getAttribute('src').split('/');
name = name[name.length-1].split('.')[0];
images[i].setAttribute('alt') = name;
}
(Also amazingly untested)
Here it is, with some simple DOM operations and a dash of regex magic:
var imgs = document.getElementsByTagName('img');
// This will extract the file name (minus extension) from the image's `src`
// attribute. For example: "images/thumb1.jpg" => "thumb1"
var name_regexp = /([^/]+)\.[\w]{2,4}$/i;
var matches;
for ( i = 0; i < imgs.length; i++ ) {
matches = imgs[i].src.match(name_regexp);
if ( matches.length > 1 ) {
imgs[i].alt = matches[1];
imgs[i].title = matches[1];
}
}
See JSFiddle for a demo.
var images = document.getElementsByTagName("img");
var count = images.length;
for (i=0; i<count; i++){
var src = images[i].getAttribute("src");
var path = src.split("/");
var fullname = path[path.length - 1];
var name = fullname.split(".");
var result = name[0];
images[i].setAttribute("alt") = result;
}
I think the real questions you should be asking is will all this actually help my SEO, because I assume that is the reason why you would like your alt tags populated?
There is some evidence that Google is getting better at reading Javascript, but will it run the scrip before it crawls the pages and add the alt text then index the page with that alt text and consider that alt text to provide additional value outside of the keywords it already found in your file names, especially considering that it rendered the script so it will probably know that the alt is just being copied form the file name. Or will Google simply index all the html and not even bother trying to run the javascript?
I would be interested to hear any additional insight others may have on this.
I personally feel there is a low probably that this will end up helping your SEO. If you are using a content management system you should probably be looking at how to add alt text via PHP by taking the variable for the page heading or title and inserting that to the alt text.
Unless you don't care about your SEO and are really doing this for text readers, then forget everything i just said.

Categories

Resources