How I get img height without append this image in DOM? - javascript

I have original image src in data-attr my element. I want get height this image. But I don't want append image to DOM. How I can get height? My code:
const imgSrc = $target
.closest('.js-photo-item')
.find('.photos__img--value')
.data('original-image');
const $img = $(new Image()).attr('src', imgSrc);
console.log($img.height()) // this return 0

const imgSrc = $target
.closest('.js-photo-item')
.find('.photos__img--value')
.data('original-image');
const $img = $(new Image()).attr('src', imgSrc);
$img.on('load', () => {
console.log($img[0].height) // return height img
});
Thanks George P user. His answer above...

You need to wait for the image to load first instead of trying to check the height right away. See, for example, https://stackoverflow.com/a/14134416/922613

Related

How to generate a html2canvas images with a hidden source (html) div

I am working in a project where I need to generate a profile picture of any member and its reviews, and some data, I started working with GDI, but it was so hard to understand, so I searched for other options and found Html2Canvas that works with javascript/jquery, everything is fine, the only thing I couldn't handle, and would like to know if there is a way to hide the source html div without breaking the result image.
Ex:
This is how is it now
This is how it should look
So, when I apply display:none on the css of the source div, the image result is like this:
And finally here is the code that I have so far
var div_to_hide = $("#mydiv:hidden");
$(function() {
$('span.stars').stars();
});
html2canvas([document.getElementById('mydiv')], {
onrendered: function (canvas) {
document.getElementById('canvas').appendChild(canvas);
var data = canvas.toDataURL('image/png');
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
}
});
$.fn.stars = function() {
return $(this).each(function() {
var val = parseFloat($(this).html());
val = Math.round(val * 4) / 4;
var size = Math.max(0, (Math.min(5, val))) * 16;
var $span = $('<span />').width(size);
$(this).html($span);
});
}
https://jsfiddle.net/ricardojriosr/6ap9Lx1f/8/
Now the question is how do I made this work showing only the image and not the HTML source. Thanks in advace.
Instead of trying to hide it before, hide (or remove) it after the canvas is rendered.
I'm not sure why var div_to_hide equals $("#mydiv:hidden"); but if you change it to var div_to_hide = $("#mydiv"); then, on line 12, after appending the image, you can run div_to_hide.hide();
And to avoid a flash of the HTML content, you can use some CSS trickery to cover up the original HTML. I made an example here, but you can adjust to fit whatever your actual needs are. https://jsfiddle.net/m5zq2kzn/
I had the same issue.
The solution that worked for me is a css trickery to position the div that I want to hide offscreen:
.offscreen {
position:absolute;
left:-10000px;
top:auto;
width:1px;
height:1px;
overflow:hidden;
}
Then use it like this:
html2canvas(document.getElementById("ticket_template"))
.then((canvas) => {
let imgData = canvas.toDataURL('image/png');
});

append string to image src using js

I've got a page where there is <img src="/images/product/whatever-image.jpg" alt="" />
I want it so that upon loading of the page, the string "?Action=thumbnail" is appended to src's value, making it src="/images/product/whatever-image.jpg?Action=thumbnail"
how do I achieve this using js?
window.addEventListener('load', function(){
/* assuming only one img element */
var image = document.getElementsByTagName('img')[0];
image.src += '?Action=thumbnail';
}, false);
Note, changing the source of the image will "re-fetch" the image from the server — even if the image is the same. This will be better done on the server-side.
Update after comment:
window.addEventListener('load', function(){
/* assuming only one div with class "divclassname" and img is first child */
var image = document.getElementsByClassName('divclassname')[0].firstChild;
image.src += '?Action=thumbnail';
}, false);
Use this:
window.onload = function() {
document.getElementById('myImage').src += "/Action=thumbnail";
};

Impliment the animation on click only at the first click?

I have multiple anchor tags with a rel="<img src"#"/>".
When I click on any <a></a>, I show a large image in another div with the rel value using a fadeIn effect.
What I want to do is check if the large image has the same src as the rel of the anchor and prevent the fadeIn effect if so.
$(document).ready(function () {
$("a.largeimg").click(function () {
var image = $(this).attr("rel");
$('.main-product-image').html('<img src="' + image + '"/>');
$('.main-product-image img').hide();
$('.main-product-image img').fadeIn();
return false;
if(src == image) {
$('.main-product-image img').show();
}
});
You can check if the rel of the anchor and the src of the image are the same and if so escape the function before the fade in code, like so:
var src = $('.main-product-image img').attr("src");
if (src == image) return false;
If I understand you question correctly, before the animation you need to confirm if the src of the image is equal to the rel attribute of the clicked element, thus preventing the animation!
JQUERY
$(document).ready(function () {
// use bind when targeting many elements
$("a.largeimg").bind("click", function () {
var $target = $('.main-product-image'), // target element
src = $target.find('img').attr("src"), // src from existent image
image = $(this).attr("rel"); // rel from clicked element
// if src different from image
if (src != image) {
$target.html('<img src="' + image + '"/>'); // append new image
$target.find('img').hide().fadeIn(); // perform the animation
}
// prevent the browser from continuing to bubble the clicked element
return false;
});
});
Ps:
Not tested, but should work just fine!

Most efficient way to modify a path with JS/jQuery

I have a load of social buttons (<img>s in a <ul>) on the right-handle side of my site.
They might have filenames such as google.png, or twitter.png.
I now want to change the src on hover to google_b.png or twitter_b.png - and I will consistently be naming my files in this way for all of them.
My question is how can I easily change the filenames to and from the _b (maintaining the file extension) without having to predifine the filenames?
At the moment my code looks like this:
$('#social li').hover(function() {
// hover in
// a bunch of code to animate a tooltip is here
var $img = $t.children('img'),
src = $img.attr('src');
// change the source to img_b.png
$img.attr('src', src);
},
function() {
// hover out
var $img = $(this).children('img'),
src = $img.attr('src');
// remove _b to make it img.png again
$img.attr('src', src);
});
Assuming files won't have fake extensions (image.png.jpeg) just split the src on ., add _b to second to last part and join again on ..
src = $img.attr('src');
var temp = src.split(".");
temp[temp.length - 2] += "_b"; //change second to last element of array
src = temp.join(".");
$('#social li').hover(function() {
// hover in
// a bunch of code to animate a tooltip is here
var $img = $t.children('img'),
src = $img.attr('src').replace(".png", "_b.png");
// change the source to img_b.png
$img.attr('src', src);
},
function() {
// hover out
var $img = $(this).children('img'),
src = $img.attr('src').replace("_b.png", ".png");
// remove _b to make it img.png again
$img.attr('src', src);
});
You could use the data function in jQuery to store the info so you won't have to constantly recalculate it.
$('#social li img').each(function(){
var image = this.src.split(".");
var onImage = image[0] + "_b." + image[1];
$(this).data("onImage",onImage);
$(this).data("offImage",this.src);
}).hover(function(){
this.src = $(this).data("onImage");
},function(){
this.src = $(this).data("offImage");
});
You could extract the src attribute directly from each image using the jquery attr() function, append characters to it like '_b' and is it on hover.

Just a part of .attr()

I have an img html block <img src="folder1/folder2/folder3/logo1.png"> positioned inside a big div like this
<div id="editorial">
<div id="img_editorial"><img src="folder1/folder2/folder3/logo1.png" /></div>
</div>
When user hovers the <div id="editorial"> (mouseover) i want to read the attribute of <img> which is folder1/folder2/folder3/logo1.png extract the logo1.png from this and add on_ to the logo ( on_logo1.png ) and then output it with jquery .html() function to overwritte <div id="img_editorial">
On mouseout i want to return to logo1.png ... because i have multiple background changes in that parent div ... so the basic functionality is to grayout a logo when mouse is over a big div (also div`s background changes ... etc) ...
So .. how can i read the <img> attribute and then extract logo1.png and not the whole folder1/folder2/folder3/logo1.png ...
You can read the attribute like this:
var img_src = $('#img_editorial img').attr('src');
This will give you:
folder1/folder2/folder3/logo1.png
Than you can split it with:
var split_img_src = img_src.split('/');
This will give you an array, something like:
split_img_src[0] = folder1;
split_img_src[1] = folder2;
split_img_src[2] = folder3;
split_img_src[3] = logo1.png;
so the last value in the array should always be the name of the file - no matter how long the directory tree is.
So you now have the file name, you can append what ever you want to it and do what ever you need.
Good luck.
Here! just a nice solution:
$('#img_editorial img').hover(function(){
imgSrc = $(this).attr('src');
var imgSplit = imgSrc.split('/');
var imgName = imgSplit[3];
$(this).attr('src', imgSrc.replace(imgName, 'on_'+imgName) );
},function(){
$(this).attr('src', imgSrc);
});
If you want, open Firebug and play with this DEMO
The following should do what you want. It just stores the original image using the jQuery .data() API and puts it back when on .mouseleave() of the <div>.
$('div#editorial').mouseenter(function() {
var originalSrc = $('img', this).prop('src');
$(this).data('originalSrc', originalSrc);
var pathComponents = originalSrc.split('/');
var logo = pathComponents.pop();
pathComponents.push('on_' + logo);
$('img', this).prop('src', pathComponents.join('/'));
}).mouseleave(function() {
$('img', this).prop('src', $(this).data('originalSrc'));
});
The demo sort of works but I have no _on image so it just 404s. I hope you get the idea :-)

Categories