Changing source of img in js and get 0 for width? - javascript

I am currently trying to set the source of an image HTML tag using jquery and then get the height and the width of the image. However, when trying to do so with the following code, the width I get is 0 and same with height :
$(document).ready(function() {
$("#image").attr("src", "https://via.placeholder.com/600x160.png?text=Testing Image");
console.log($("#image").width());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<img id="image" />
</div>
I am trying to do this in order to change the image src of the same HTML tag and get the new width and height.
I found that it was due to the image not loaded in the DOM so I tried some things I found on internet as the two following snippets but with the same result of a width of 0 and a height of 0 :
$(document).ready(function() {
$(`<img id='image' src='${"https://via.placeholder.com/600x160.png?text=Testing Image"}'>`).appendTo('#container');
console.log($("#image").width());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
</div>
$(document).ready(function() {
let image = new Image();
image.src = "https://via.placeholder.com/600x160.png?text=Testing Image";
image.id = "image";
$('#container').append(image);
console.log($("#image").width());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
</div>
I do not know if you can understand my needs, but I would really appreciate help there.
Thanks in advance.

You should use a load event, in order to wait until the image is loaded and has been shown up
see below snippet :
using Jquery :
$(document).ready(function() {
var $image = $("#image");
$image.attr("src", "https://via.placeholder.com/600x160.png?text=Testing Image");
$image.on("load", function() {
console.log($(this).width(),"X",$(this).height());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<img id="image" />
</div>
using pure js :
let image = new Image();
image.src = "https://via.placeholder.com/600x160.png?text=Testing Image";
image.id = "image";
image.addEventListener("load", function(event) {
console.log(this.width ,"x",this.height)
});
let container = document.getElementById("container")
container.appendChild(image);
<div id="container" ></div>

You need to listen image's onload event listener:
const img = new Image();
img.setAttribute('src', 'https://via.placeholder.com/150');
console.log('img width before load', img.width);
img.addEventListener('load', () => console.log('img width after load', img.width));
document.body.appendChild(img);

Related

Replace a smaller image with a larger one (after the larger image loads)

I have a few images of superheroes. These are in divs along with much larger images of astronomical objects. These larger images take a while to load. I want the astronomical images to replace the superhero images after they've loaded.
Here's what I have so far: https://jsfiddle.net/vmpfc1/5typ7pnp/1/
HTML:
<body>
<div class="image-wrapper">
<div class="pix"style="background: url('http://baltimorepostexaminer.com/wp-content/uploads/2012/07/spider-man2_pole_4681.jpg'); height:200px;width:200px;">
</div>
<div class="true-image" style="background: url('http://m1.i.pbase.com/o9/27/876727/1/151851961.JlvdQ9xW.GreatCarinaKeyholeandRedHoodNebulae3454x2566pixelsimproved3.jpg')"></div>
</div>
<div class="image-wrapper">
<div class="pix"style="background: url('https://upload.wikimedia.org/wikipedia/en/7/75/Comic_Art_-_Batman_by_Jim_Lee_%282002%29.png'); height:200px;width:200px;">
</div>
<div class="true-image" style="background:url(' https://www.nasa.gov/sites/default/files/706439main_20121113_m6triptych_0.jpg')"></div>
</div>
</body>
js:
setTimeout(function () {
$('.true-image').attr('style').on('load', function () {
$('.pix')({
'background-image': 'url(' + $(this).attr('src') + ')'
});
});
}, 0);
css:
.true-image {
display : none;
}
I am a javascript newbie -- is there a decent way to make the larger space images replace the superhero placeholders?
Is there an easier way to do this in HTML5?
Edited Answer to reflect changes:
<div style="background-image: url('https://i.imgur.com/sOcRl3M.jpg'); height:400px;width:400px" rel="https://i.imgur.com/xr7CRQo.jpg">
</div>
<div style="background-image: url('https://i.imgur.com/1m0NwgN.png'); height:400px;width:400px" rel="https://i.imgur.com/nlFPkc4.jpg">
</div>
Then you can have jQuery to loop through all images which has a rel attribute. 2 or 2,000 images, it does not matter.
$('div[rel]').each(function() {
var rel = $(this).attr('rel');
var self = $(this);
var img = new Image();
$(img).load(rel, '', function() {
self.css('background-image', 'url('+rel+')');
});
});
You can see it working here: https://jsfiddle.net/83zLumuk/4/

How to take screenshot of a div using javascript?

Say for example i have a div with image source
<div>
<p class="row">With custom CSS</p>
<img src="/images/midhun.jpg">
</div>
On button click i need to open this image screen shot in another div
Can you tell the steps to take the screen shot of that image
Assuming, you want to show the image in other div.
HTML:
<div id="main">
<img src="https://lh5.googleusercontent.com/-XOGfvAHr7HQ/UvoUItkZMZI/AAAAAAAAHJk/IJz5JcUB9dw/w520-h274-no/scopes_in_directives.png" />
</div>
<div id="copy">
</div>
<button id="myButton">Click</button>
Javascript:
$('#myButton').on('click', function() {
$('#copy').html($('#main').html());
});
Demo: https://jsfiddle.net/tusharj/uapf99nt/
You don't need to take any screenshot. The image is already loaded, so you can just show the same image again:
HTML
<div id="originalDiv">
<img src="/images/midhun.jpg">
</div>
<div id="secondDiv">
<img src="" />
</div>
CSS
#secondDiv { display:none }
jQuery
$(document).on('click', '#button', function() {
var img = $('#originalDiv > img').attr('src');
$('#secondDiv > img').attr('src', img).show();
});
look here. it attempts to render a part of the dom, into an image
http://html2canvas.hertzen.com/
Check this link to take a screenshot..
$(function() {
$("#btnSave").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
canvas.toBlob(function(blob) {
saveAs(blob, "Dashboard.png");
});
}
});
});
});

How To Change Image And Link On Click As Toggle Function?

I want a Pure JavaScript code that will change an image and also its link to another image and another link on same place as toggle function. I have a web page and I have Anchors Links button as <img src="DownArrow.png"/> and I want that after clicking on this image, first it will lead you to the DIV2 and then it will change the code to <img src="UpArrow.png"/>. How to do this using pure JavaScript? Waiting for perfect reply and code?
This should work:
var link = document.querySelector('#arrow a');
link.onclick = function() {
var image = document.querySelector('#arrow a img');
if(this.href.slice(-1) === '1') {
this.href = '#DIV2';
image.src = 'https://cdn1.iconfinder.com/data/icons/nuvola2/48x48/actions/1uparrow.png';
} else {
this.href = '#DIV1';
image.src = 'https://cdn1.iconfinder.com/data/icons/nuvola2/48x48/actions/1downarrow.png';
}
}
See it in action here: http://jsfiddle.net/TM9ap/7/
Note that I've changed the href attribute in the link to #DIV1 like this <a href="#DIV1">
<!DOCTYPE html>
<html>
<title></title>
<head></head>
<body>
<a href = "#DIV1" style="color:BLACK;" onclick="execute();">Click me
<img src="UpArrow.png" />
</a>
<div id="DIV1" ></div>
<div id="DIV2" ></div>
<script>
function execute()
{
if ( document.getElementsByTagName("a")[0].getAttribute("href")==="#DIV1"){
var img = document.getElementsByTagName("img")[0];
img.setAttribute("src","DownArrow.png");
img.parentNode.setAttribute("href","#DIV2");
}
else
{
var img = document.getElementsByTagName("img")[0];
img.setAttribute("src","UpArrow.png");
img.parentNode.setAttribute("href","#DIV1");
}
}
</script>
</body>
</html>

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