How to add parameter to image url with JavaScript - javascript

I can embed images on my page with specified width and height (like this: <img src="image.php?w=100&h=100">)
I want to load different image sizes depending on device screen width:
100x100 for screen widths lower than 600px and 200x200 in other cases. As I understand php knows nothing about user screen so I have to use JS.
This didn't work:
<img src="image.php?<script>document.write('w=100&h=100')</script>">
That worked:
<script>document.write('<img src="image.php?w=100&h=100">')</script>
Is that a correct way for doing this? Any consequences I should take into consideration?

You can use that code. But I think that bst way is to change src of images on the server side.
function addParams(w, h) {
var img = document.querySelectorAll("img.withParams");
for (var i = 0; i < img.length; i++) {
img[i].src = img[i].src + "?w=" + w + "&h=" + h;
}
}
window.addEventListener("load", function () {
addParams(10, 10);
})
<img class="withParams" src="img.php"/>
<img src="img.php" />
<img class="withParams" src="img.php" />

Related

Change image source folder for mobile version with javascript

Sorry I'm a newbie with JS and I've been having trouble with some JS I found here on stackoverflow. My situation is that I have a div with two images inside, and I want to change the source path of those images when the window is less than 480px. My code is this:
<div id="bigFoto">
<img src="img/photo1.jpg" alt="text for alt" id="photo1">
<img src="img/photo2.jpg" alt="text for alt" id="photo2">
</div>
And The current script I'm running is:
$(window).resize(function(){
var width = $(window).width();
if (width < 481) {
$("#bigFoto img#photo1").attr("src","img/mobile/photo1.jpg");
$("#bigFoto img#photo2").attr("src","img/mobile/photo2.jpg");
}
else{
$("#bigFoto img#photo1").attr("src","img/photo1.jpg");
$("#bigFoto img#photo2").attr("src","img/photo2.jpg");
}
});
This script is working right, but now let's say I want that div to have 20 images, my guess is that I would have to add every one of them in this script right?
The real question: is there a way to target all images instead and just add the /mobile part on the source path? ,since the filename remains the same.
Thanks so much for your help!
You can use jQuery's each function to loop through all the elements returned by a query
$(window).resize(function(){
var width = $(window).width();
if (width < 481) {
$("#bigFoto img").each(function(index){
var src = $(this).attr("src")
var photoName = src.substr(src.lastIndexOf("/"));
$(this).attr("src", "img/mobile/"+photoName)
})
}
else{
$("#bigFoto img").each(function(index){
var src = $(this).attr("src")
var photoName = src.substr(src.lastIndexOf("/"));
$(this).attr("src", "img/"+photoName)
})
}
});

Change image src if the width is larger then original image

I have an application that defines the width of an image through html like this:
↓↓↓↓↓↓↓↓↓↓↓↓
<img id="teste" class="item" src="../img/fotos/4medium.jpg" style="width: 430px; display: block; margin-top: -7px; margin-left: 0px; max-width: 9999em; height: auto;"/>`
But, if the width of the image is less than 430px, the app expands the image possibly warping or pixelating it.
Is there a way to check if the style="width" is bigger than the original picture width and, if so, change the src to another image?
I think that it should look something like this:
if ($('#teste').width() > $(4medium.jpg).width()) {
$('img').attr('src', '../img/fotos/4larger.jpg');
} else {
$('img').attr('src', '../img/fotos/4medium.jpg');
}
Thanks in advance.
Ideally this is something you would check with a script on the server (since otherwise you potentially will have to download both images to the client). Something like this should work:
var testImg = new Image();
testImg.src = '../img/fotos/4medium.jpg';
testImg.onLoad = check_image_size( testImg );
Then test the width to see if you need to load the larger image:
function check_image_size( obj ) {
var url = obj.src;
if ( obj.width > 430 )
url = '../img/fotos/4larger.jpg';
$('#teste').attr( 'src', url );
}
This is an ugly approach (and potentially slow because it potentially could load both images), but I'm not sure if there is a more elegant way to do it client side.
Try:
var teste_img = document.getElementById('teste');
var teste_width = teste_img.clientWidth;
var medium_img = document.getElementById('medium');
var medium_width = teste_img.clientWidth;
if(test_width > medium_width ){
$('img').attr('src', '../img/fotos/4larger.jpg');
}else{
$('img').attr('src', '../img/fotos/4medium.jpg');
}

how to show image only when it is completely loaded?

I have an img tag on my web page. I give it the url for an IP camera from where it get images and display them. I want to show image when it is completely loaded. so that I can avoid flickering. I do the following.
<img id="stream"
width="1280" height="720"
alt="Press reload if no video displays"
border="0" style="cursor:crosshair; border:medium; border:thick" />
<button type="button" id="btnStartLive" onclick="onStartLiveBtnClick()">Start Live</button>
javascript code
function LoadImage()
{
x = document.getElementById("stream");
x.src = "http://IP:PORT/jpg/image.jpg" + "?" + escape(new Date());
}
function onStartLiveBtnClick()
{
intervalID = setInterval(LoadImage, 0);
}
in this code. when image is large. it takes some time to load. in the mean time it start showing the part of image loaded. I want to display full image and skip the loading part Thanks
Preload the image and replace the source of the <img /> after the image has finished loading.
function LoadImage() {
var img = new Image(),
x = document.getElementById("stream");
img.onload = function() {
x.src = img.src;
};
img.src = "http://IP:PORT/jpg/image.jpg" + "?_=" + (+new Date());
}
You can use the complete property to check if the image has finished loading. However, I think there are other issues with your code, mainly you are repeatedly loading the same image. Instead, you should load it only once and then check the complete property in an interval.
Something like this should work:
function LoadImage()
{
x = document.getElementById("stream");
x.src = "http://IP:PORT/jpg/image.jpg" + "?" + escape(new Date());
x.style.visibility = 'hidden';
}
function CheckIsLoaded() {
x = document.getElementById("stream");
if (x.complete) x.style.visibility = 'visible';
}
function onStartLiveBtnClick()
{
LoadImage();
intervalID = setInterval(CheckIsLoaded, 0);
}
The following appears to work fine for me
<img src="/path/to/image.png"
class="d-none"
onload="this.classList.remove('d-none')"
>
Basically I hide the img element and show it only after the image is loaded. Here d-none is the bootstrap class that defines display:none but you can define your own class if you are not using bootstrap.
If you would like to reserve the space for the image even adding a default background, you can use a wrapper div with ratio ratio-4x3 (for bootstrap) or its equivalance CSS (e.g. padding a wrapper with height=0 in proportion to width), and set a background to img through css.

change image and caption

I am trying to work out a way to change the text that goes along with an image that is changed with javascript...
var x = 0;
var images = new Array(".jpg", ".jpg", ".jpg", ".jpg", ".jpg");
var i = setInterval(auto, 10000);
function auto() {
x++;
if (x == images.length) x = 0;
document.getElementById('bigImage').src = images[x];
}
function changeImage(img, imagetitle) {
document.getElementById('bigImage').src = img;
/* document.getElementById('mainimagetitle').innerHtml = imagetitle; */
}​​​
The commented part is how i suppose I could possibly change the text that goes with the image. How do i code the html. Should i use a with the id mainimagetitle?
If so, where and how do i add the different texts i want to show and hide?
As I see from your posting, this should do the job.
<img id="bigImage" src="img1.jpg" alt="" />
<div id="mainimagetitle"></div>
Be sure to add a (filled) src tag or you will get strange results in IE. As you start with the second image (x++ before the change) this will be no problem. Happy accident I think. ;-)
// Edit: Of course any element will do as long as you use the right id. But you didn't tell us what html you use (xhtml/html5/...).
You could potentially have another array that stores the captions for each of the images
var captions = ['Caption 1', 'Caption 2', ...];
Assuming the mainimagetitle is an id of a <p> element, you could do:
function changeImage(img, imagetitle) {
document.getElementById('bigImage').src = img;
document.getElementById('mainimagetitle').innerText = imagetitle;
}​​​
You can see the full example, based on your code here.

jQuery find height of an image even if it is not set in the HTML

I have, what I think is, a strange issue. I am running a simple query that finds the largest image on a page. Here is some test data - all images are 32x32 but one is sized to 300x300.
<img src="app/assets/images/icons/blue.png" />
<img src="app/assets/images/icons/error.png"/>
<img src="app/assets/images/icons/info.png" height="300" width="300"/>
If I run a simple query like this:
$('img').each(function(){
console.log($(this).height());
});
I will get 0,0,300 — and not 32,32,300.
Can anyone point me to a better method of finding the size the image is being rendered at?
Thanks.
If the image is "natively" sized, i.e. no width or height are present in the HTML, you'll need to wait for the image to load before you know its size. I use this:
jQuery("img").each(function(){
var img = jQuery(this);
if (img.attr("complete")) {
console.log(img.height());
} else {
img.load(function(){
console.log(img.height());
});
}
});
Make sure you do it after the image is ready in $(img).load(), then it will work. Try JavaScript to verify:
function iLoad(isrc) {
var oImg = new Image();
oImg.src = isrc;
if (oImg.complete) {
window.alert(oImg.src + ' ' + oImg.width + ' x ' + oImg.height);

Categories