I have this function to print the image dimensions of all <img> having the attribute [proto].
When I try the function with this each method, it only returns a function.
What is the mistake?
function size(){
var $img = $('img[proto]');
$($img).each(function(){
var height = $(this).height;
var width = $(this).width;
$(this).parent().find('p').remove();
$(this).parent().append('<p class="size">' + width + '-' + height + '</p>');
});
}
size();
These are functions not properties, height and width:
var height = $(this).height();
var width = $(this).width();
Change you elements declartion. Because you do it like this: $($('img[proto]')). This way you cast your elements two time into jQuery.
width and height are functions, not properties. So you need to add brackets.
function size() {
$('img[proto]').each(function() {
var height = $(this).height(),
width = $(this).width();
$(this).parent().find('p').remove();
$(this).parent().append('<p class="size">' + width + '-' + height + '</p>');
});
}
size();
I would even prefer to only get the elements you needed once. The way you did it casts this four times into an jQuery object and search two times for the parent. The performance could be saved.
var element = $(this),
parent = element.parent(),
height = element.height(),
width = element.width();
parent.find('p').remove();
parent.append('<p class="size">' + width + '-' + height + '</p>');
And if you want to execute the function directly, you can use an IIFE or just remove the function around and execute it directly.
(function() {
$('img[proto]').each(function() {
// ...
});
})();
Related
Context
I've used the "Intersection Observer API" to build an infinite scroll image gallery. Basically this API allows me to load more items when a certain dummy DOM element enters the viewport.
Prototype
Currently the prototype is implemented for an “iPhone X” (375x812) mobile device only. See: http://urbexco-acceptance.droppages.com/min_rep_ex_working (use Chrome DevTools 'inspect' device toolbar to select the right resolution). The image gallery is generated based on 57 items in the "database". When scrolling down, first 15 elements are loaded, then 15 more elements are loaded, then another 15 elements are loaded into the DOM, then another 10 elements are loaded, and finally 2 elements are loaded. When there are still more than 15 items left to be loaded, they are added using the following logic:
function addItems(n){
// Append new items to .items-wrapper
var items = document.querySelector('.items-wrapper');
for (var i = 0; i < n; i++) {
var url = 'https://img01.ztat.net/article/spp-media-p1/09742e38c25b3e1d9716e02f8e76e87d/89fc0bda6a2c446a8e9e0d8adbc9a4fe.jpg';
width = 170.5;
height = 246;
var newDiv = document.createElement('div');
newDiv.classList.add('item');
items.appendChild(newDiv);
newDiv.innerHTML = "<img src=" + '"' + url + '"' + "width=" + '"' + width + '"' + "height=" + height + "/>";
}
}
Minimal Working Example (no mobile view possible)
https://jsfiddle.net/9jqgzymo/
Objective
Since image width and height are currently hardcoded, I am now trying to assign width and height dynamically based on the image url. I try to achieve this using the getMeta() function:
function addItems(n){
// Append new items to .items-wrapper
var items = document.querySelector('.items-wrapper');
for (var i = 0; i < n; i++) {
var url = 'https://img01.ztat.net/article/spp-media-p1/09742e38c25b3e1d9716e02f8e76e87d/89fc0bda6a2c446a8e9e0d8adbc9a4fe.jpg';
getMeta(url);
}
}
function getMeta(url){
var img = new Image();
img.onload = function(){
res = calculateAspectRatioFit(this.width, this.height, 170.5, 246)
var newDiv = document.createElement('div');
newDiv.classList.add('item');
var items = document.querySelector('.items-wrapper');
items.appendChild(newDiv);
newDiv.innerHTML = "<img src=" + '"' + url + '"' + "width=" + '"' + res.width + '"' + "height=" + res.height + "/>";
};
img.src = url;
}
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return { width: srcWidth*ratio, height: srcHeight*ratio };
}
Challenge
When implementing it this way, I see that - on initiation - already 30 items from the "database" where added to the DOM. Sometimes even all of them? Currently the non-working prototype is implemented for an “iPhone X” (375x812) mobile device only. See: http://urbexco-acceptance.droppages.com/min_rep_ex_not_working (use Chrome DevTools 'inspect' device toolbar to select the right resolution). For a minimal working example, see: https://jsfiddle.net/k3p20qno/
Key question
What is the reason that with my new implementation, on initiation, already 30 or more items are added to the DOM? How can I fix it?
Well the problem lies in here :
function getMeta(url){
var img = new Image();
img.onload = function(){
res = calculateAspectRatioFit(this.width, this.height, 170.5, 246)
var newDiv = document.createElement('div');
newDiv.classList.add('item');
var items = document.querySelector('.items-wrapper');
items.appendChild(newDiv);
newDiv.innerHTML = "<img src=" + '"' + url + '"' + "width=" + '"' + res.width + '"' + "height=" + res.height + "/>";
};
img.src = url;
}
Above code does an async operation with onload event. So it doesn't wait to image to be loaded.
If you turn this into a function that returns a promise you will get the result that you expect. And you should await where you call the function. That way when you add the intersection element it will add it as the last element of the items wrapper. If you don't await it will be added as the first element because the loading of the images will be async and will happen later.
function getMeta(url){
var img = new Image();
const p = new Promise(resolve =>{
img.onload = function(){
console.log( this.width+' '+ this.height );
res = calculateAspectRatioFit(this.width, this.height, 170.5, 246)
var newDiv = document.createElement('div');
newDiv.classList.add('item');
var items = document.querySelector('.items-wrapper');
items.appendChild(newDiv);
newDiv.innerHTML = "<img src=" + '"' + url + '"' + "width=" + '"' + res.width + '"' + "height=" + res.height + "/>";
resolve()
};
})
img.src = url;
return p;
}
Fiddle
Edit: Put the resolve() in the right position which is inside the load function
While i am trying to get the size of image so, that i can append same size of div to explain the image. Images are coming dynamically so how can i get the image size that appear on browser not the real size of image. I have tried following code but does not work when parent class is smaller the image.
$('img').each(function(i) {
$currentImg = $(this);
imgTextshow = $currentImg.attr('imgtext');
var img = new Image();
img.onload = function() {
$currentImg.after("<div class='img-fscreen' style='width:" + this.width + "px; max-width:" + $currentImgParent + "'>" + imgTextshow + "</div>");
}
img.src = $(this).attr('src');
});
If you use the following lines of code inside of the onload handler, they should give you the correct dimensions:
$currentImg.width();
$currentImg.height();
simply because those methods return the width/height of the img DOM element.
Just use below line
img.onload = function() {
$currentImg.after("<div class='img-fscreen' style='width:" + $currentImg.width() + "px; max-width:" + $currentImgParent + "'>" + imgTextshow + "</div>");
}
Please go to: www.designedbychristian.com/template_2
(so far being tested in chrome)
When you click design a bunch of thumbnails appear.
I am trying to use the .each selector to get the src of the image. I want to take that value and apply it to a div that will appear when clicked. (I know how to program that part)
My problem is when I click the thumb nail my alert is giving me the value of all of the thumbnails.
my code is this:
function spawnImages() {
N = 1
for (i = 1; i <= 9; i++) {
var gal = document.getElementById('gallary')
var newDIV = '<img onclick="imageView()" src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
$('.gallary').prepend(newDIV)
var min = 3;
var max = 70;
var s = Math.floor(Math.random() * (max - min + 1)) + min;
var test = $(('.imageNumber' +N)).css("left", s + "%")
var min = 3;
var max = $(this).height();
var max = 70;
var s = Math.floor(Math.random() * (max - min + 1)) + min;
var test = $(('.imageNumber' + N)).css("top", s + "%")
var min = -45;
var max = 45;
var s = Math.floor(Math.random() * (max - min + 1)) + min;
var test = $(('.imageNumber' + N)).css("-webkit-transform", "rotate(" + s + "deg)")
var test = $(('.imageNumber' + N)).css("transform", "rotate(" + s + "deg)")
var test = $(('.imageNumber' + N)).css("-ms-transform", "rotate(" + s + "deg)")
N++
}
}
function imageView() {
$(".thumb-nail").each(function () {
var imageSrc = $(this).attr('src');
alert($(this).attr('src'));
//$('.images').css("background-image", "url("+imageSrc+")");
//$('.images').css("background-size", "cover");
//$('.blackForeground').css("visibility", "visible");
//$('.images').css("visibility", "visible");
})
};
Just use jquery event handlers, get rid of the onclick call in your html and just add this in your javascript.
$(".thumb-nail").on('click', function(){
var imageSrc = $(this).attr('src');
alert($(this).attr('src'));
//$('.images').css("background-image", "url("+imageSrc+")");
//$('.images').css("background-size", "cover");
//$('.blackForeground').css("visibility", "visible");
//$('.images').css("visibility", "visible");
});
EDIT: didn't think about the images being created dynamically, Popnoodles answer is the right one
pass clicked element reference like this:
var newDIV = '<img onclick="imageView(this)" src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
Function:
function imageView(element) {
var imageSrc = $(element).attr('src');
alert($(element).attr('src'));
}
This is exactly how the jQuery API describes the .each() method:
Iterate over a jQuery object, executing a function for each matched element.
When you called $('.thumb-nail') it returned ALL of the elements with the class thumb-nail in a jQuery object. Then when you called .each( function() {} ) on that object, the loop iterated over all of the returned elements.
The easiest way to handle click events in jQuery, is to use the .on() method, as others have pointed out in their answers.
Also, as #Popnoodles mentioned, since these elements are created dynamically, you may need to run your $().on() call explicitly after these elements are created. For that reason, you might wrap it into your spawnImages() function, rather than putting it inside $() as #Popnoodles indicates (i.e. not $( $(element).on('click',function(){}), as $( ) is equivalent to $(document).ready.
The simplest change is this
// send this element to the function
var newDIV = '<img onclick="imageView(this)" src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
function imageView(el) {
var imageSrc = $(el).attr('src');
alert($(el).attr('src'));
};
But it's nice to do things in a more standard fashion...
First get rid of this onclick="imageView()"
var newDIV = '<img src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
Since these elements are created dynamically you will need to bind the click event to document or another ancestor that exists, and delegate to each ".thumb-nail".
You also need to run this procedure only when dom is ready ($(function(){...});).
$(function(){
$(document).on('click', ".thumb-nail", function () {
var imageSrc = $(this).attr('src');
alert($(this).attr('src'));
//$('.images').css("background-image", "url("+imageSrc+")");
//$('.images').css("background-size", "cover");
//$('.blackForeground').css("visibility", "visible");
//$('.images').css("visibility", "visible");
});
});
I have the following JS code that changes the width depending on value of the data-percentage HTML attribute:
var addRule = (function (sheet) {
if(!sheet) return;
return function (selector, styles) {
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
}
}(document.styleSheets[document.styleSheets.length - 1]));
var i = 101;
while (i--) {
addRule("[data-percentage='" + i + "%']", "width:" + i + "%");
}
See the demo: http://jsfiddle.net/YYF35/
Instead of width, for some elements I want to change their height.
How can I change the code so that depending on class of the div I change the height or width of element (depending on the data-percentage attribute number of course)?
I don’t want to create a different HTML attribute for it, like so:
while (i--) {
addRule("[data-percentage-width='" + i + "%']", "width:" + i + "%");
addRule("[data-percentage-height='" + i + "%']", "height:" + i + "%");
}
jQuery can be used as well. Any ideas?
Your code is adding rules. If you really want to be doing that, just add more rules:
var i = 101;
while (i--) {
addRule("[data-percentage='" + i + "%'].change-width", "width:" + i + "%");
addRule("[data-percentage='" + i + "%'].change-height", "height:" + i + "%");
}
Now, elements with the change-width class will have their width modified, and elements with the change-height class will have their height modified (and you can use both if you like).
Try this:
$("div[data-percentage]").each(function(){
$(this).css({
width: $(this).attr('data-percentage')
//height: $(this).attr('data-percentage')
});
});
http://jsfiddle.net/YYF35/1/
jQuery method .width() was used to get the width of the generated element as:
html:
<div class='row-fluid' id='photo-preview'></div>
javascript:
for(i = 0;i < 4;i++){
var imageSpan = "<div class='span3' id='span_" + i + "'><img src='" + images[i] +"'></div>"
$('#photo-preview').append(imageSpan);
var w = $('#span_' + i).width();
console.log(w);
}
But it got the incorrect value of width. It was the value of percentage instead of pixel. E.g, w should be 400 (400px) but the js got 80 (80%).
I thought the problem may be because the element was dynamically generated. In the console I can got the right value with .width() when all the elements were loaded.
Any ideas to work around with it?
You have to wait for the load event of the image before you can get the correct height.
var img = '<img src="img_path.jpg">';
$(img)
.load(function() {
console.log("width", $(this).width());
})
.appendTo('#photo-preview');
Edit: To match with your example :
html:
<div class='row-fluid' id='photo-preview'></div>
javascript:
for(i = 0;i < 4;i++){
var img = "<img src='" + images[i] +"'>";
$(img)
.load(function() {
console.log("width", $(this).width());
})
.appendTo("<div class='row-fluid' id='photo-preview'>")
.appendTo('#photo-preview');
}
Try using offsetWidth
I.E.
var w = $('#span_' + i).offsetWidth;
console.log(w);
Here's a really silly fiddle I made. I set the width to 80%. If you go to the console, you should see the pixel width (448 px)
http://jsfiddle.net/bwm5s/