Modifying all images (src) without id on page after onload - javascript

I ve given up finding a crossbrowser image solution which makes me happy.
I now want to make it the "mobile first" way of the cost of bandwith for destkops.
The plan: Ship mobile sized images to all clients.
Then i am able to get the viewport size of the browser which works fine.
My CSS is switching as the follows: <= 1000 px mobile view >=1001 desktop view.
But then: I thought i would save images in the same paths with different file extensions. Lets say i would save them as the follows
/img/myimage-mobile.jpg
/img/myimage-normal.jpg
/img/myimage-highres.jpg
initial load would look like
<img src="img/myimage-mobile.jpg" alt="#" />
Now my question: How can i get all img tags and change the extension of the src attribute? When detecting a viewport width >=1001 i want to replace all "-mobile.jpg" with "-normal.jpg" and larger ~1400 with "myimage-highres.jpg".
Thats what i got so far:
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
getting the viewport size and then i found this which is getting the entire src attribute:
var images = document.getElementsByTagName('img');
var srcList = [];
for(var i = 0; i < images.length; i++)
{
srcList.push(images[i].src);
srcList.push(images[i].src);
}

I don't think this is the best method but it does change the image paths but this will also work on window resize. If other developers want to edit this to clean it up or improve something then feel free to do so.
Would it not be better to detect the users device rather than using the browser height/width?
var defaultimg="normal";
function _Imgs(){
var imgsize;
var Pw=document.documentElement.clientWidth;
var Ph=document.documentElement.clientHeight;
if(Pw<800||Ph<300){ // Change this to Set width for mobiles
imgsize="mobile";
}else{
imgsize="normal";
}
var MyImgs=document.getElementsByTagName("IMG");
for(var i=0; i<MyImgs.length; i++) {
MyImgs[i].setAttribute("src",MyImgs[i].src.replace(defaultimg, imgsize));
}
//Change variable value to allow toggle on window resize
defaultimg=imgsize;
}
window.onload=_Imgs;
window.onresize=_Imgs;

With Jquery you can do it like this
$('img').each(function(){
var fix = $(this).attr('src').replace('mobile', 'normal');
$(this).attr('src', fix);
})
To detect the viewport size you can do this:
var height = window.innerHeight;
var width = window.innerWidth;
Then just make a function wrapping it all together:
window.onload = function(){
var height = window.innerHeight;
var width = window.innerWidth;
if(height < 1000 && width < 400){
$('img').each(function(){
var fix = $(this).attr('src').replace('mobile', 'normal');
$(this).attr('src', fix);
})
}
}
or with pure javascript:
window.onload = function(){
var height = window.innerHeight;
var width = window.innerWidth;
if(height < 1000 && width < 400){
var imgs = document.getElementsByTagName('img');
for(i=0;i<imgs.length;i++){
var fix = imgs[i].src.replace('mobile', 'normal');
imgs.src = fix;
}
}
}

Related

Change an element width in px when resizing the window

How can I change an element with a fixed width in px when i resize the window? I need to use an absolute unit, i can not use relative units like % or vw.Every time the window is resized with 1 px i need to decrease the element width by 0.2px.
I tried to use the window resize eventListener but i don't know what calculations needs to be done.
What you want can be achieved by using javascript. I've created a logic to do that :
<script>
function myFunction() {
var initialscreenwidth = window.innerWidth; //Set Initial Screen Width
setInterval(function() { //looping the script
var screenwidth = window.innerWidth;
var difference = initialscreenwidth - screenwidth; //Calculating the change in screen-size
if (difference != 0) { //Checking if there is a change in width
var element = document.getElementById('demo');
var style = window.getComputedStyle(element, null).getPropertyValue('font-size'); //Getting default font-size of the element
var initialfontsize = parseFloat(style);
var fontdifference = -(parseFloat(difference) / 5); //1px change in screen-size = 0.2px change in font-size
var newfontsize = initialfontsize + fontdifference;
var newfontsizepx = newfontsize + "px";
if (newfontsize > 1) {
document.getElementById("demo").style.fontSize = newfontsizepx;
}
}
initialscreenwidth = window.innerWidth;
}, 300); //reloads in every 300ms
}
myFunction();
</script>
Paste this at the end of your body section, somehow using this in the head section is not working.

javascript load image on scroll

i want to build my own lazy images using only javascript.
so far, this is my code :
<img src="images1.jpg" data-src="images2.jpg" />
var body = document.body,
html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight),
screen = screen.height;
img = document.getElementsByTagName("img");
window.addEventListener("scroll", function() {
for(var i = 0; i < img.length; i++) {
if (img[i].clientHeight >= height - screen) {
var data = img[i].getAttribute("data-src");
img[i].setAttribute('src','');
img[i].setAttribute("src", data);
}
}
});
the problem is, the image data-src did not execute into src attribute on scroll event.
i want it to execute when the images about 200px before the viewport.
how to doing this? and what's wrong with my code? is it possible that my if condition not correct?
Your code works just fine, you need to add }); at the end, though.
var body = document.body,
html = document.documentElement,
height = Math.max(
body.scrollHeight,
body.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight),
screen = screen.height;
img = document.getElementsByTagName("img");
window.addEventListener("scroll", function() {
for(var i = 0; i < img.length; i++) {
if (img[i].clientHeight >= height - screen) {
var data = img[i].getAttribute("data-src");
img[i].setAttribute('src', data);
}
}
});
<img src="https://placeholdit.imgix.net/~text?txtsize=63&bg=FF6347&txtclr=ffffff&txt=Image-1&w=350&h=250"
data-src="https://placeholdit.imgix.net/~text?txtsize=63&bg=63FF47&txtclr=ffffff&txt=Image-1&w=350&h=250" />
<img src="https://placeholdit.imgix.net/~text?txtsize=63&bg=FF6347&txtclr=ffffff&txt=Image-2&w=350&h=250"
data-src="https://placeholdit.imgix.net/~text?txtsize=63&bg=63FF47&txtclr=ffffff&txt=Image-2&w=350&h=250" />
<img src="https://placeholdit.imgix.net/~text?txtsize=63&bg=FF6347&txtclr=ffffff&txt=Image-3&w=350&h=250"
data-src="https://placeholdit.imgix.net/~text?txtsize=63&bg=63FF47&txtclr=ffffff&txt=Image-3&w=350&h=250" />
<img src="https://placeholdit.imgix.net/~text?txtsize=63&bg=FF6347&txtclr=ffffff&txt=Image-4&w=350&h=250"
data-src="https://placeholdit.imgix.net/~text?txtsize=63&bg=63FF47&txtclr=ffffff&txt=Image-4&w=350&h=250" />
I don't get what you mean by "200px before the viewport". Could you explain it better? If you don't want all images to change at the same time, should consider the offetTop of each image and the scrollTop position. http://jsbin.com/xexeho/edit?html,js,output
If you can mention the dimensions of the images, it would make more sense. However I am still trying to attempt to answer your question as I think the scroll event in your code wasn't triggering at all. Try making your img tag slightly below the viewport so that scroll works
Also for the calculation use window.innerHeight as it gives right height of the viewport subtracting height of the addressbar etc.
<img src="images1.jpg" data-src="images2.jpg" style="position:absolute;top:1169px"/>
<script>
var body = document.body,
html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight),
screen = window.height;
img = document.getElementsByTagName("img");
window.addEventListener("scroll", function() {
console.log("Checking if the scroll event is triggered...");
for(var i = 0; i < img.length; i++) {
if (img[i].clientHeight >= height - screen) {
var data = img[i].getAttribute("data-src");
img[i].setAttribute('src','');
img[i].setAttribute("src", data);
}
}
});
</script>
OR
try using events like mousewheel and/or DOMMouseScroll which does not expect body to be actually scrollable.
Hope this helps!
Checkout source of lazy loading plugin from todd motto.
It's pretty useful view others implementation.

How do I change a HTML ID with Javascript on page load after getting window size?

I am wondering how I can use Javascript to get a windows size and then set (really clear) an HTML ID with it.
I am currently working on a site that has a "default" navigation ID of "access" which I want to blank out if the windows size is less than 800 px wide.
This is the page I am working on and if the ID is cleared I can then setup the mobile navigation to work with bootstrap.
`window.onload = function() {
var w = window.innerWidth;
if(w < 800) {
document.getElementById('access').removeAttribute('id');
}
}
window.onload = function() {
var w = window.innerWidth;
if(w < 800) {
document.getElementById('access').removeAttribute('id');
}
}
window.onresize = function() {
var w = window.innerWidth;
if(w < 800) {
document.getElementById('access').removeAttribute('id');
}
}
Use
var w = window.innerWidth;
to get the width of the page.
and then,
window.onload = function() {
if(w < 800) {
document.getElementById('access').removeAttribute('id');
}
}
You probably want to add this functionality in resize too.
EDIT: put the code in window.onload
Based on the comment,
window.onload = function() {
var accessElem = document.getElementById('access');
var updateAccess = function() {
var w = window.innerWidth;
if(w < 800) {
accessElem.removeAttribute('id');
}
else {
accessElem.setAttribute('id', 'access');
}
};
window.onresize = updateAccess; // call updateAccess on resize
updateAccess(); // call once on load to set it.
};
Also, in my opinion, adding/removing id is not a great idea.

javascript image resizing in jquery

I came upon a script for resizing images dynamically for fitting a specific width here. I modified it for my own web app and it works great part of the time, but for some reason the function will sometimes randomly not trigger the if statement when the image does indeed have a larger width then I’m desiring so the image never resizes. I put in a set timeout hoping that the timeout would give the browser time to read the image. But no luck any ideas as to why it would not trigger?
Side note: this is for a mobile web app, is there something with HTML5 that I could use?
var maxWidth = 200;
var imgWidth = $('#locImg').width();
console.log(imgWidth);
setTimeout(function () {
if( imgWidth > maxWidth) {
newWidth = maxWidth;
var newHeight = $('#locImg').height() / ( $('#locImg').width() / maxWidth);
$('#locImg').height(newHeight).width(newWidth);
console.log($('#locImg').width());
$('#loc').css('visibility','visible');
}
else {
$('#loc').css('visibility','visible');
}
},750);
You could use something like this to ensure the image is fully loaded:
var maxWidth = 200;
var imgWidth = $('#locImg').width();
var image = new Image();
image.src = $('#locImg').attr("src");
image.onload = (function () {
if( imgWidth > maxWidth) {
newWidth = maxWidth;
var newHeight = $('#locImg').height() / ( $('#locImg').width() / maxWidth);
$('#locImg').height(newHeight).width(newWidth);
console.log($('#locImg').width());
$('#loc').css('visibility','visible');
}
else {
$('#loc').css('visibility','visible');
}
});
this way it only starts the resize after the image has fully loaded.

Auto-scroll to the bottom of a div

I have a div with overflow set to scroll which essentially streams data line by line off a file. I'd like to scroll automatically to the bottom of the div whenever the stream overflows, but without using a "Click here to scroll to bottom" button.
I already know of the scrollTop = scrollHeight solution, but that requires some kind of event trigger on the client's side. I don't want this element to be interactive; it should scroll by itself.
Is there any way to achieve this?
A lot of the scrollHeight implementations didn't work for me, offsetHeight seemed to do the trick.
Pretty sure that scrollHeight tries to move it to the bottom of the height of the static element, not the height of the scrollable area.
var pane = document.getElementById('pane');
pane.scrollTop = pane.offsetHeight;
There's no way to automatically scroll an element to the bottom. Use element.scrollTop = element.scrollHeight.
If you don't know when the element is going to resize, you could add a poller:
(function(){
var element = document.getElementById("myElement");
var lastHeight = element.scrollHeight;
function detectChange(){
var currentHeight = element.scrollHeight;
if(lastHeight != currentHeight){
element.scrollTop = currentHeight;
lastHeight = currentHeight;
}
}
detectChange();
setInterval(detectChange, 200); //Checks each 200ms = 5 times a second
})();
Some old code of mine with a running example that will stay at the bottom when new content is added, if the user scrolls it will not more it to the bottom.
var chatscroll = new Object();
chatscroll.Pane =
function(scrollContainerId)
{
this.bottomThreshold = 25;
this.scrollContainerId = scrollContainerId;
}
chatscroll.Pane.prototype.activeScroll =
function()
{
var scrollDiv = document.getElementById(this.scrollContainerId);
var currentHeight = 0;
if (scrollDiv.scrollHeight > 0)
currentHeight = scrollDiv.scrollHeight;
else
if (objDiv.offsetHeight > 0)
currentHeight = scrollDiv.offsetHeight;
if (currentHeight - scrollDiv.scrollTop - ((scrollDiv.style.pixelHeight) ? scrollDiv.style.pixelHeight : scrollDiv.offsetHeight) < this.bottomThreshold)
scrollDiv.scrollTop = currentHeight;
scrollDiv = null;
}

Categories