First image in <body> greater than 200 px Using Jquery - javascript

For social media sharing I am trying to get the first image URL which is greater than 200px using jQuery. This is my code which is not working:
$("body img").each(function() {
var $minHeight = 200;
if ($(this).height() > $minHeight) {
$(this).attr('src')
}
});
After getting the right image I need to change the default image URL in content="default-image.png" below:
<meta property="og:image" name="twitter:image" content="default-image.png"/>
This is a working selector for meta tag I found:
$('meta[property=og\\:image]').attr('content','new-image.png');
I Found My Code Is Working But...
$("body img").each(function() {
var $minHeight = 200;
if ($(this).height() < $minHeight) {
$x = $(this).attr('src')
}
});
$('meta[property=og\\:image]').attr('content',$x);
$(".share a[href*='pinterest']").prop("href","https://pinterest.com/pin/create/button/?url=http://mywebsite.com/mypage&media="+$x);
But above script is not working with greater than sign as needed if ($(this).height() > $minHeight)

So, when you do $("body img") jquery returns an array of elements.
If I am understanding it correct, you need the image which is of ACTUAL HEIGHT but not the CSS provided height. In this case:
var ImagesGreaterThan200Height =jQuery.grep($("body img"), function( img, i ) {
if(img.naturalHeight > 200)
return img;
});
From the above code, you will get an array of Images which are greater than 200px in height and for the first image you just need to do:
ImagesGreaterThan200Height[0] // This returns the first Image
Hope this helps!

Related

Script Not Working on Website But Working on JsBin, Jsfiddle After One Refresh

This is a simple jquery script which finds a image greater than 300px and show url in paragraph. And this code working on online editor sites like jsbin but same code not working on website.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<main>
<p>
</p>
<img src="http://icons.iconarchive.com/icons/icons-land/metro-raster-sport/128/Soccer-Ball-icon.png">
<img src="http://www.iconarchive.com/download/i65352/icons-land/metro-raster-sport/American-Football-Ball.ico">
<img src="http://simpleicon.com/wp-content/uploads/football.png">
</main>
<script>
$(function() {
$('main img').each(function() {
$Height = 300;
if ($(this).height() > $Height) {
$image = $(this).attr('src');
$('p').text($image);
return false;
}
});
});
</script>
</body>
</html>
But if you change Only the greater-than sign to less-than sign in jquery if statement, then script will work on both website and online editor and showing image url everytime you refresh it.
How to make this script work to also display a image url which is greater than some pixels?
I found a way which makes it work also on website:
Running the script in
$(window).on("load",function(){
}
Your code works before images are loaded. You should give it a bit delay .
Try this;
$(function() {
setTimeout(function(){
$('main img').each(function() {
$Height = 300;
if ($(this).height() > $Height) {
$image=$(this).attr('src');
$('p').text($image);
return false;
}
});
},150);
});
The jQuery code executes as soon as the DOM is ready— it does not wait for the images to load! Therefore, none of the images have a height when the script searches for them.
When you refresh, the images are loaded instantly from the cache, in time for jQuery to catch them.
Take a look at this StackOverflow thread for an idea of how to trigger your function in response to each image's onload event!
e.g.,
$('main img').on('load', function(){
if ($(this).height() > 300)
$('p').text($(this).attr('src'))
;
});
Note that this code should supplement the code you've already written, since the jQuery documentation points out how the load event can fail to fire if the images are already in the cache.
calling .widht() or .height() also calculates padding assigned to the element.
try remove padding from the element, or you can simply subtracts the padding from the element
i.e;
remove padding:
main > img{padding: 0;}
Calculate the image height and remove padding:
$(function() {
$img = $('main img');
$img.each(function() {
var tp = parseInt($img.css('padding-top'), 10);
var bp = parseInt($img.css('padding-bottom'), 10);
$Height = 300;
if ($(this).height() - (tp + bp) > $Height ) {
$image=$(this).attr('src');
$('p').text($image);
return false;
}
});
});
Hope this will help. :)
just add https: before //ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js and then try.
note : your system must be connected to the internet or provide system file url for jquery.min.js
Javascript in both JSBin links are same,there is no differences.
If you want your function to work properly just add "$(document).ready" on your function like:-
$( document ).ready(function() {
$('main img').each(function() {
$Height = 300;
if ($(this).height() > $Height) {
$image=$(this).attr('src');
$('p').text($image);
return false;
}
});
});
Hope,this will for both web & JSBin.
Please read: -https://learn.jquery.com/using-jquery-core/document-ready/

Jquery Display round tag image under image issue

I want to add round tag Images(25*25 pixel) on all Image tags in the html Dom.
It works but with my code the position sometimes changes and it often displayed under the Image.
Here is my code:
jQuery("img").each(function() {
var image = jQuery(this);
if ((image.width() >= 512) && (image.width() <= 2048)){
image.parent().css('display', 'inline-block');
var top_pos = image.offset().top+200, left_pos = image.offset().left+150;
image.parent().append('<div class="tag_image first_tag_image1" id="first_draggable1" style="position:absolute;'+'top:'+top_pos+'px;'+'left:'+left_pos+'px;">');
//do something
}
});
Anybody who knows what to do?
If any question please add a comment.
You have to use :before.
For example image.before('//some code')

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)
})
}
});

How to get height of element with dynamically loaded images inside

I have a lot of tables and in last td in last tr I put message from back-end. There could be not only text, but the images (url to them in tags), so they load dynamically. I need to get the height of this table and if it more than 400 I add some contant.
Firstly, I did this:
$("table[name]='forum'").each(function() {
var height = $(this).height();
if (height > 400) {
var redirect = $("#backUrl").val() + "#" + $(this).find("[name]='answ'").attr("id");
$(this).find("tr:last-child > td:last-child").append(function() {
return "<div></div><a style='float: right' href='"+ redirect + "'><img src='/images/arrow_up.png'></a>";
});
};
});
But it didn't work for tables with images. Than I googled that for img I should use load() and add:
$(this+"> img").load(function() {
height += $(this).height();
});
but I understand, that this is wrong, cause img could be loaded after this block is done. I did some other actions, but it won't affect as I wanted.
What is the solution of this problem? Because it calculates height of whole element without img tag.
To get the final table height(if the img will affect the height, or you can pre-set some max height maybe), you must wait all images loaded.
var table = $(this), imgs = table.find("img"), len = imgs.length;
imgs.one('load', function() {
len--;
//now all image loaded
if (len == 0) {
//here you got the final height
height = table .height();
//do stuffs here
}
}).each(function() {
if (this.complete)
$(this).load();
});
$(this).find("img").load(function() {
height += $(this).height();
});

How can i know if all <img> loaded in div using jQuery

How can i know if all loaded in div using jQuery
i want to do this after load all img in #slider div
var imgHeight = $("#slider img").height();
alert(imgHeight);
You can use the load event
$('#slider img').load(function(){
var imgHeight = $(this).height();
alert(imgHeight);
});
if there are more than one image, and you only want to obtain the height after they have all loaded, try this code
var img = $('#slider img');
var length = img.length;
img.load(function(){
length--;
if(length === 0){
alert("All images loaded");
};
});
Well, I've tested the code, and it appears that the problem hasn't got anything to do with the code. When loading the page with the images already in the cache, this is what I get:
Strangely, this does not occur when I force the browser not to use the cache.
Try this:
Attach an onload event listener to each image in the slider.
In the listener:
Give the current image a custom attribute to mark it is 'ready'.
Check if all images are ready. If so, do your thing (i.e. alert(imageHeight))
untested:
(function(){
var slider=document.getElementById('slider'),
images=slider.getElementsByTagName('img'), image, i=-1;
while (image=images[i]) {
image.onload=function(){
this['data-ready']=true;
var image, i=-1;
while (image=images[i]) if (!image['data-ready']) return;
// all images are ready; do your thing here
// ...
}
}
}());

Categories