Basically what I am trying to do is have images fill a div whilst maintaining their aspect ratio. So I am using jquery to identify whether they are portrait or landscape, and set either width or height from there.
My problem is the code gives all the images landscape class. I am at my wits end to know why...
Thank you!
HTML
<div class="prop">
<div class="propimage"><img src="{#image}" alt="{#prop_name}"></div>
<div class="propname">{#prop_name}</div>
<div class="propdescription">{#description}</div>
<div class="propprice">{#price}</div>
</div>
CSS
.portrait img {
width: 100%;
}
.landscape img {
height: 100%;
}
.propimage img {
display: block;
}
img {
max-width: none;
}
.propimage {
width: 100%;
height: 300px;
overflow: hidden;
float: left;
}
SCRIPT
<script>
$(".propimage").each(function(){
// Uncomment the following if you need to make this dynamic
//var refH = $(this).height();
//var refW = $(this).width();
//var refRatio = refW/refH;
// Hard coded value...
var refRatio = 240/300;
var imgH = $(this).children("img").height();
var imgW = $(this).children("img").width();
if ((imgW/imgH) < refRatio){
$(".propimage").addClass("portrait");
} else {
$(this).addClass("landscape");
}
})
</script>
Please upload You code on js fiddle or paste the link so we can see working example of your code. Meanwhile just try this code
<script>
$(".propimage").each(function(){
// Uncomment the following if you need to make this dynamic
//var refH = $(this).height();
//var refW = $(this).width();
//var refRatio = refW/refH;
// Hard coded value...
var refRatio = 240/300;
var imgH = $(this).children("img").height();
var imgW = $(this).children("img").width();
if (imgW=<200 || imgH<=300)){
$(this).children("img").css("width","100%");
$(this).css("width","100%");
} else {
$(this).children("img").css("height","100%");
$(this).css("height","100%");
}
})
</script>
Related
There are images loaded via ajax request to the side.
The problem is that all these images have different size and just some of them needs to have a special width and height.
I need to change the size after these images have been attached to the dom. I mean after they have been attached to this div.
<div id="myID" class="justAClass"></div>
How is it possible to access images after they have been attached to the DOM ?
Previously I attempted the following:
if($('#myID .justaClassName img').attr('width') > 1000
&& if($('#myID .justaClassName img').attr('height') <= 3000){
$('#myID .justaClassName img').css({
'width' : '200px',
'height' : '400px'
});
}
You can access your images using the following javascript:
const images = document.querySelectorAll('#myID img')
Three possible solutions follow:
1) Use CSS
2) Select the image directly with jQuery
3) Use a MutationObserver
1) First and foremost always try to solve a style problem with CSS. You may be able to set max-width and max-height properties to constrain your images to their containing parent.
#myId img {
/* try different values here like your original 200 x 400 */
max-width: 100%;
max-height: 100%;
}
2) However, this likely does not meet all your requirements however. You stated a specific condition for image resize, and that is width > 1000 and height <= 3000. This leads me to believe you want images smaller than that to stay their original size while images larger than that get resized to 200 x 400.
If possible, you should modify the code directly by selecting the image correctly with jQuery: $('#myID img').
3) In the event you do not control the code which is changing your page, you can setup a MutationObserver to watch for DOM changes. Whenever the image changes, an observer can determine its size and adjust accordingly.
The solution I propose is useful in such cases where you do not control all the code. It may be that some images are dynamically loaded by a script you cannot edit.
var target = document.getElementById('myID');
var config = {
attributes: false,
childList: true,
characterData: false
};
var observer = new MutationObserver(function(mutations) {
// the first image added to #myID
var img = mutations[0].addedNodes[0];
if (img.width > 1000 && img.height <= 3000) {
img.width = 400;
img.height = 200;
}
});
observer.observe(target, config);
Putting it all together in a demo:
var doodles = [
'https://www.google.com/logos/doodles/2017/freedom-day-and-enoch-sontonga-5748739204448256-2x.jpg',
'https://www.google.com/logos/doodles/2017/kings-day-2017-5641966854340608.15-2xa.gif',
'https://www.google.com/logos/doodles/2017/childrens-day-2017-mexico-5079016900919296-2x.png'
];
window.onload = function () {
var target = document.getElementById('myID');
var config = {
attributes: false,
childList: true,
characterData: true
};
var observer = new MutationObserver(function (mutations) {
var img = mutations[0].addedNodes[0];
if (img.width > 400 && img.height <= 3000) {
img.width = 400;
img.height = 200;
}
});
observer.observe(target, config);
target.onclick = function () {
var r = Math.floor(Math.random() * doodles.length);
target.innerHTML = '<img src="' + doodles[r] + '">';
};
};
#myID {
display: inline-block;
width: 500px;
height: 500px;
border: solid black 3px;
border-style: dashed;
padding: 14px;
margin: 3px;
}
img {
border: solid black 1px;
}
<div id="myID" class="justAClass">Click to Load</div>
I'm new to jQuery and i'm still in the process of learning HTML and CSS. I wanted to have a responsive image on the homepage of my website that scaled itself with the user's browser window. I found this at github: https://github.com/gutierrezalex/photo-resize.git
but i think i might be using it wrong, since i can't get it to work for me.
Here's my html:
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
</script>
<reference path="jquery-1.5.1.min.js" />
<script src="jquery-photo-resize.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("img").photoResize()
});
</script>
</head>
and here's the jquery-photo-resize.js file:
function photoResize($) {
"use strict";
$.fn.photoResize = function (options) {
var element = $(this),
defaults = {
bottomSpacing: 10
};
function updatePhotoHeight() {
var o = options,
photoHeight = $(window).height();
$(element).attr('height', photoHeight - o.bottomSpacing);
}
$(element).load(function () {
updatePhotoHeight();
$(window).bind('resize', function () {
updatePhotoHeight();
});
});
options = $.extend(defaults, options);
};
}
Like i said, i'm a novice, so please let me know what i'm doing wrong, and how i can achieve my desired effect.
You don't need jquery for this. Just set a class name and then in your style sheet use a width. If you only set a width it'll auto size the height to maintain the aspect ratio. Same goes for setting the height only. If you set both your aspect ratio may be off. The width can be a percentage of the current element. You could also use vw (view port width). Also calc is super helpful.
{ width:75%}
Update:
.cropper {
width: 75px;
height: 75px;
overflow: hidden;
position: relative;
}
.cropped {
width: 100px;
position: absolute;
left: -12.5px;
top: -12.5px;
}
<div class="cropper">
<img class="cropped" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/SIPI_Jelly_Beans_4.1.07.tiff/lossy-page1-256px-SIPI_Jelly_Beans_4.1.07.tiff.jpg"/>
</div>
Here is code :
CSS :
.featured { overflow:hidden;
border:2px solid #000;
position:relative;}
.featured img { width:100%; position:relative;}
#pos_1 { width:200px; height:190px; }
#pos_2 { width:150px; height:250px; }
#pos_3 { width:350px; height:150px; }
HTML :
<div id="topGallery">
<article class="featured" id="pos_1">
<img src="abc.jpd" class="attachment-post-thumbnail wp-post-image" alt="piano" />
</article>
</div>
Javascript :
jQuery(document).ready(function($) {
///HOME PAGE - image resizing
function imageLoaded() {
var w = $(this).width();
var h = $(this).height();
var parentW = $(this).parent().width();
var parentH = $(this).parent().height();
//console.log(w + '-' + h + '-' + parentW + '-' + parentH);
//if (w >= parentW){ //always true because of CSS
if (h > parentH){
$(this).css('top', -(h-parentH)/2);
} else if (h < parentH){
$(this).css('height', parentH).css('width', 'auto');
$(this).css('left', -($(this).width()-parentW)/2);
}
//}
}
$('#topGallery img').each(function() {
if( this.complete ) {
imageLoaded.call( this );
} else {
$(this).one('load', imageLoaded);
}
});
});
Why do I get a line-break? I use the following: White-space: nowrap; but when I fill in the span a line-break appears. What is causing this?
function insertLinkHoverImage(datei,datei2,verlinkung)
{
var doc = document.getElementById("frame").contentWindow.document;
var range = doc.getSelection().getRangeAt(0);
var nnode = doc.createElement("span");
var width = 0;
var height = 0;
var image = doc.createElement("img");
image.src = "http://www.galliano.cc/Test_seite/cms/uploads/"+datei;
//Wenn Bild hochgeladen wurde
image.onload = function() {
document.getElementById("imgwidth").value = image.width;
document.getElementById("imgheight").value = image.height;
var alink = doc.createElement("a");
var classDatei2 = "";
alink.href = verlinkung;
classDatei2 = datei.replace(".","-");
nnode.setAttribute("style","white-space: nowrap; background-image:url(http://www.galliano.cc/Test_seite/cms/uploads/"+datei+"); width:"+document.getElementById("imgwidth").value+"px; height: "+document.getElementById("imgheight").value+"px; display: block; background-repeat: no-repeat;");
alink.appendChild(nnode);
range.insertNode(alink);
}
}
If you look at your JavaScript, you have:
var nnode = doc.createElement("span");
and then you have:
nnode.setAttribute("style","white-space: nowrap;
background-image:url(...);
width:"+document.getElementById("imgwidth").value+"px;
height: "+document.getElementById("imgheight").value+"px;
display: block; background-repeat: no-repeat;");
So the span is by default, an inline element, but then you specify display: block in your inline style, which makes it a block level element, and that will give you your line break.
Try using display: inline-block.
I'm trying to build a draggable column based layout in JavaScript and having a bit of hard time with it.
The layout comprises of 3 columns (divs), with two dragable divs splitting each. The idea is that they are positioned absolutely and as you drag the draggers, the columns' respective widths, and left values are updated.
The three columns should always span the full width of the browser (the right most column is 100% width), but the other two should remain static by default when the browser is resized (which is why i'm using px, not %).
My code isn't working as of yet, I'm relatively new to JavaScript (which is why I don't want to use jQuery).
Having said that, there must be a more efficient (and cleaner) way of achieving this with less code that works (without reaching for the $ key).
If anyone with some awesome JS skills can help me out on this I'd be super-appreciative.
Here's the fiddle I'm working on http://jsfiddle.net/ZFwz5/3/
And here's the code:
HTML
<!-- colums -->
<div class="col colA"></div>
<div class="col colB"></div>
<div class="col colC"></div>
<!-- draggers -->
<div class="drag dragA" style="position: absolute; width: 0px; height: 100%; cursor: col-resize; left:100px;"><div></div></div>
<div class="drag dragB" style="position: absolute; width: 0px; height: 100%; cursor: col-resize; left: 300px;"><div></div></div>
CSS:
body {
overflow:hidden;
}
.col {
position: absolute;
height:100%;
left: 0;
top: 0;
overflow: hidden;
}
.colA {background:red;width:100px;}
.colB {background:green; width:200px; left:100px;}
.colC {background:blue; width:100%; left:300px;}
.drag > div {
background: 0 0;
position: absolute;
width: 10px;
height: 100%;
cursor: col-resize;
left: -5px;
}
and my terrible JavaScript:
//variabe columns
var colA = document.querySelector('.colA');
var colB = document.querySelector('.colB');
var colC = document.querySelector('.colC');
//variable draggers
var draggers = document.querySelectorAll('.drag');
var dragA = document.querySelector(".dragA");
var dragB = document.querySelector(".dragB");
var dragging = false;
function drag() {
var dragLoop;
var t = this;
var max;
var min;
if (dragging = true) {
if (this == dragA) {
min = 0;
max = dragB.style.left;
} else {
min = dragA.style.left;
max = window.innerWidth;
}
dragLoop = setInterval(function () {
var mouseX = event.clientX;
var mouseY = event.clientY;
if (mouseX >= max) {
mouseX = max;
}
if (mouseY <= min) {
mouseY = min;
}
t.style.left = mouseX;
updateLayout();
}, 200);
}
}
function updateLayout() {
var posA = dragA.style.left;
var posB = dragB.style.left;
colB.style.paddingRight = 0;
colA.style.width = posA;
colB.style.left = posA;
colB.style.width = posB - posA;
colC.style.left = posB;
colC.style.width = window.innerWidth - posB;
}
for (var i = 0; i < draggers.length; i++) {
draggers[i].addEventListener('mousedown', function () {
dragging = true;
});
draggers[i].addEventListener('mouseup', function () {
clearInterval(dragLoop);
dragging = false;
});
draggers[i].addEventListener('mouseMove', function () {
updateLayout();
drag();
});
}
I see a couple of things wrong here. First of all, the mousemove event only fires on an element when the mouse is over that element. You might have better luck registering a mousemove listener on the parent of your div.drag elements, then calculating the mouse's position inside that parent whenever a mouse event happens, then using that position to resize your columns and your draggers.
Second, I'm not quite sure what you're trying to do by registering a function with setInterval. You're doing pretty well with registering event listeners; why not continue to use them to change the state of your DOM? Why switch to a polling-based mechanism? (and the function you pass to setInterval won't work anyway - it refers to a variable named event, which in that context is undefined.)
This is just a little example... I hope it can help you :)
window.onload = function() {
var myDiv = document.getElementById('myDiv');
function show_coords(){
var monitor = document.getElementById('monitor');
var x = event.clientX - myDiv.clientWidth / 2;
var y = event.clientY - myDiv.clientWidth / 2;
monitor.innerText = "X: " + x + "\n" + "Y: " + y;
myDiv.style.left = x + "px";
myDiv.style.top = y + "px";
}
document.onmousemove = function(){
if(myDiv.innerText == "YES"){show_coords();}
}
myDiv.onmousedown = function(){
myDiv.innerText = "YES";
}
myDiv.onmouseup = function(){
myDiv.innerText = "NO";
}
}
I made an if function to check if the width is < 100px. For some reason it hides everything. Anyone know why?
$(document).ready(function() {
var pic = $(".pic");
// need to remove these in of case img-element has set width and height
$(".pic").each(function() {
var $this = $(this);
$this.removeAttr("width");
$this.removeAttr("height");
var pic_real_width = $this.width();
var pic_real_height = $this.height();
if(pic_real_width<100){
$(this).css("display","none");
}
});
});
You're using pic when you should be using $(this):
$(".pic").each(function() {
var $this = $(this);
$this.removeAttr("width");
$this.removeAttr("height");
var pic_real_width = $this.width();
var pic_real_height = $this.height();
alert(pic_real_width);
});
You should also watch for images that are resized with CSS.
Instead of
$this.removeAttr("width");
$this.removeAttr("height");
try
$this.css({width: 'auto', height: 'auto'});
Try this:
$(document).ready(function() {
$(".pic").each(function() {
var pic = $( this );
pic.removeAttr("width");
pic.removeAttr("height");
var pic_real_width = pic.width();
var pic_real_height = pic.height();
alert(pic_real_width);
});
});
I tried every solutions here but none worked for me so I created my own script and it works in all browsers including IE. Heres my script:
$(function(){
var sbar = $(".sidebar").outerHeight(true);
var pcont = $(".post_content").outerHeight(true);
if(sbar < pcont){
$(".sidebar").css("min-height",pcont+"px");
}
});
/*** CSS ***/
.sidebar{
float:left;
min-height: 500px;
width:180px;
}
.post_content{
float:left;
min-height: 500px;
width:593px;
}
I hope this will work with you too!!
$this.css({width: 'auto', height: 'auto'});
try it