Hide partial background repeat - javascript

Consider these simple CSS rules:
jsFiddle
div#container {
width: 50%;
height: 260px;
background-image: url('Image.png');
background-repeat: repeat-x;
}​
The problem is that I only want full images. If there is not enough space for another duplicate, it should NOT be shown.
I've never heard that CSS provides a rule for it. So how can I achieve it in JavaScript (jQuery already included)?

This is not possible with current CSS rules. You can repeat once, or repeat forever. The alternative is to shrink the size of the containing element to fit the nearest repeating point in either CSS (if you know the width before page load) or JS (if you don't).
Here's the latter implentation using jQuery:
var $container = $("#container");
var bgImg = extractUrl($container.css("background-image"));
var $img = $("<img />", { "src" : bgImg }).hide().appendTo("body");
$container.width(nearest($("#container").width(), $img.width()));
$img.remove();
function extractUrl(input) {
// remove quotes and wrapping url()
return input.replace(/"/g, "").replace(/url\(|\)$/ig, "");
}
function nearest(n, v) {
n = n / v;
n = Math.floor(n) * v;
return n;
}
Example fiddle

This will work for percentage widths and auto adjusts on sreen resize.
$(window).on('load resize', function () {
var img = $('<img/>');
img.attr('src', 'http://upload.wikimedia.org/wikipedia/commons/0/0c/Fussball.jpg').load(function () {
var height = this.height;
var width = this.width;
var divWidth = $('#containerwrap').width();
var extra = divWidth % width;
$('div#container').width(divWidth - extra);
});
});
div#container {
width: 670px;
height: 260px;
margin:0 auto;
background: url('http://upload.wikimedia.org/wikipedia/commons/0/0c/Fussball.jpg') left center;
background-repeat: repeat-x;
}
#containerwrap{
width:100%;
height: 260px;
background-color:#000000;
}
<div id="containerwrap">
<div id="container">
Test
</div>
</div>
http://jsfiddle.net/upjkd/14/show

As the width is fixed by the server, and the server knows the size of the image - why not construct the image to be correct and forget the repeat, or make the width the appropriate size so it will fit whole number of images?

See http://jsfiddle.net/upjkd/10/
var img=document.createElement('img');
img.src="http://upload.wikimedia.org/wikipedia/commons/0/0c/Fussball.jpg";
document.body.appendChild(img);
var con=document.getElementById('container'),
numImages=Math.round(con.clientWidth/img.clientWidth);
con.style.backgroundSize=con.clientWidth/numImages+'px';
document.body.removeChild(img);
You can use Math.round(con.clientWidth/img.clientWidth) to determine the number of repetitions of the image, and then use con.style.backgroundSize=con.clientWidth/numImages+'px' to be sure that the number of images is an integrer (only full images).

Related

How to resize of a image base on screen size

How can I resize of a image base on screen size. Example:
I have a tag (width:1349, height: 449) and a image in div (width:78, height:78). When display image in div I fix for width of image is 60 and height is 60. I saw in mobile screen then the size of image still keep state so now I want to image display automatic resize base on screen example: in iPhone 4 the image have size (20x20) or percent of it in the screen. How can I use the formular for calculate it? This is my code jquery for calculate it.
var mw = $("#c").width();
var mh = $("#c").height();
console.log();
var img = new Image();
img.src = './img/photo-circle.png';
var wdImg = img.width;
var hiImg = img.height;
var ratioImg = wdImg/hiImg;
var ratioDiv = mw/mh;
if (ratioDiv > 1) {
var newwd = wdImg*(mh/hiImg);
alert(newwd);
} ;
You should be using percentages to achieve dynamic resizing of your elements. Then, as long as the parents are also dynamically resizing, their children will as well. For example, width: 30%; instead of width: 100px;
use the css unit vh and vw
each unit is worth 1% of the screen size
http://caniuse.com/#feat=viewport-units
example:
.item {
height: 20vw;
width: 20vw;
}
If the screen width is 100pixels, .item would be 20px by 20px
Simply you can use a bootstrap class called "img-responsive" at your img tag .
That's all , It will be responsive on any screen.

How to change div height if browser height is less than a given number of pixels?

I have a div that I want to be one of two sizes.
If browser window height is smaller than a given height, then it uses the smaller height for the div
However, if browser window height is larger than given height, then it uses larger height for the div
I tried the following code but it's not working. I need help to get it working.
Here is the jsbin: http://jsbin.com/oFIRawa/1
And here is the code I have so far:
page.html
<div id="theDiv"> </div>
style.css
#theDiv {
background: #000;
border: 2px solid #222;
width: 300px;
height: 400px;
margin: 50px auto 0 auto;
}
script.js
$(document).ready(function () {
// call the method one time
updateWindowSize();
// subscribe the method to future resize events
$(window).resize(updateWindowSize);
// variables
var updateWindowSize = (function(){
var minAllowedWindowHeight = 500;
var largerDivHeight = 400;
var smallerDivHeight = 300;
// actual updateWindowSize function
return function(){
var winHeight = $(window).height();
var newHeight = winHeight < minAllowedWindowHeight ? smallerDivHeight : largerDivHeight;
$('#theDiv').height(newHeight);
};
})();
});
You can do this in CSS my good sir. It's called responsive design!
#media (max-height:500px) {
Enter special css conditions for 500px height.
}
#media (max-height:200px) {
Enter special css conditions for 200px height.
}
This is more commonly used for max-width because it can tell us when someone is using a mobile device (something like 360px max-width), then we can modify our page to look nice on mobile. No fancy javascript needed!
var threshhold;
var smallerHeight = 50;
var largerHeight = 100;
if ($(window).height() < threshold)
$('#theDiv').height(smallerHeight);
else
$('#theDiv').height(largerHeight);
FIDDLE
Demo

Retrieve size of background image after scaling with jQuery?

I have the following simple code to get me the background-image dimensions, but it grabs the size of the original image, not the scaled one I have in my div. I want to get pixel dimensions after scaling, is there any way to do that?
var actualImage = new Image();
actualImage.src = $("#chBox").css('background-image').replace(/"/g, "").replace(/url\(|\)$/ig, "");
actualImage.onload = function () {
width = this.width;
height = this.height;
}
EDIT:
The CSS to scale the background-image:
#chBox {
height:100%;
width:100%;
background-repeat:no-repeat;
background-image: url(../content/frog/1.jpg);
background-position: center;
-webkit-background-size: contain; /*for webKit*/
-moz-background-size: contain; /*Mozilla*/
-o-background-size: contain; /*opera*/
background-size: contain; /*generic*/
}
Instead of getting the dimensions of the actual image, you need to get the $('#someImage').css('width') and $('#someImage').css('height') of the image you want.
edit:
#someImage img {
width: 100px;
height: auto;
}
<td id="image">
<img id="someImage" src="image.jpg">
<script type="text/javascript">
alert($('#someImage').css('width'));
</script>
</td>
the code above would alert "100px". and of course if you use some jQuery to change the width of the image, like $('#someImage').css('width','300px'), the code would the update and alert "300px"
The code is doing what you're telling it to do. I don't believe there is a way to grab the 'scaled' size.
Alright, thanks to everyone for their responses but I thought of a bit of a workaround. I would like to see this feature in a later release of jQuery (grabbing scaled width, height) but with some math, it ain't so bad.
Essentially,
// create a fake image and load the original from background-img src
var actualImage = new Image();
actualImage.src = $("#chBox").css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
actualImage.onload = function() {
// get original values
var origWidth = this.width;
var origHeight = this.height;
var width = 0;
var height = 0;
// need to bump it 140px as it seems the div's left comes from the super-container
var bump = 140;
// if the image is fat rather than tall,
if(origWidth > origHeight){
// set width for description to width of bg-img container
var width = $("#chBox").width();
// set left
$(".description").css("left", bump);
// calculate height and set bottom
height = (width * origHeight) / origWidth;
var blankSpace = $("#chBox").height() - height;
$(".description").css("bottom", (blankSpace/2));
} else {
// if image is tall,
var height = $("#chBox").height();
// calculate width
width = (height * origWidth) / origHeight;
// set left
var setLeft = $("#chBox").width();
$(".description").css("left", (setLeft/2) - 58); //wtf, 58?
// set bottom to 0
$(".description").css("bottom", 0)
}
$(".description").width(width);
}
There's quite a bit of site-specific stuff there, but basically I ran some algebra to find the proportions of the image. If it's a fat image rather than a tall image, the width of the container is the scaled width. The height is equal to the scaled width * original image height divided by the original image width. For some reason (and if someone could help with this I'd be grateful) the margin: 0 auto; property of my CSS doesn't work when you change up the div width, so I had to manually center it.

How do I get dynamically fluid images depending on browser window aspect ratio?

This might not be a simple question, but I try my best.
I have this example site: http://lotvonen.tumblr.com/
I have a little piece of javascript that automatically calculates the height of the inner browser window and sets that number as image wrapper div's height. Height of the image inside the wrapper is 100% of the wrapper, so that I get nice, full screen images on all normal screen sizes.
This works wonderfully on screens that are more wide than tall (desktops, laptops, etc).
But!
With screens that are more tall than wide (smartphones, iPads etc), the images get clipped from sides. I don't want that, so I have a temporary solution to have media query assigning height to auto and width to 100%, when browser screen max-width is 1024, so that no clipping occurs. But it's not a very good solution, and breaks at certain resolutions. It also destroys my JS with lower resolutions (eg. 800x600).
Here's the JS:
<script type="text/javascript">
var elems = document.getElementsByClassName('img'),
size = elems.length;
for (var i = 0; i < size; i++) {
var img = elems[i];
var height = (window.innerHeight) ? window.innerHeight: document.documentElement.clientHeight;
img.style.height=(height)+'px';
}
</script>
and here's my CSS:
.img {
max-width:100%
}
.img img {
width:auto;
}
.img img {
height:100%;
}
#media only screen and (max-width: 1024px) {
.img {
height:auto !important;
}
.img img {
height:auto !important;
max-width:100%;
}
and here's the div:
<li><div class="img"><img src="{PhotoURL-HighRes}" alt="{PhotoAlt}"/></div>
How do I get it so, that when the browser window is more tall than wide (eg. 720x1024), the images adjust by width, and when the browser window is more wide than tall (eg. 1024x720) the images adjust like they do now (by height, with the JS).
Is this possible at all? Is there a simple CSS fix to this or do I need to mess more with JS?
Thanks in advance!
You could also get the aspect in javascript on a regular basis and then add a class to the body object that would specify if it was 4:3, widescreen, or portrait. Then make it run on an interval in case the window changes size.
Example
CSS
.43 img { width: auto; }
.widescreen img { width: 100%; }
.portrait img { height: 100%; }
JavaScript
var getAspect = function(){
var h = window.innerHeight;
var w = window.innerWidth;
var aspect = w / h;
var 43 = 4 / 3;
var cssClass = "";
if (aspect > 43) {
cssClass = "widescreen";
}
else if (aspect === 43) {
cssClass = "43";
}
else {
cssClass = "portrait";
}
$("body").addClass(cssClass); // Using jQuery here, but it can be done without it
};
var checkAspect = setInterval(getAspect, 2000);
I would suggest getting the aspect ratio first in javascript. Use window.innerHeight and windows.innerWidth, and make the necessary division. Then, make this a condition. When the screen in wider than its height, set the image in css to width: 100%. Otherwise, set height: 100%.

Scrollpane on the bottom, css is hacky, javascript is hard

I want to put a bar on the bottom of my page containing a varying number of pictures, which (if wider than the page) can be scrolled left and right.
The page width is varying, and I want the pane to be 100% in width.
I was trying to do a trick by letting the middle div overflow and animate it's position with jquery.animate().
Like this:
Here is a fiddle without the js: http://jsfiddle.net/SoonDead/DdPtv/7/
The problems are:
without declaring a large width to the items holder it will not overflow horizontally but vertically. Is this a good hack? (see the width: 9000px in the fiddle)
I only want to scroll the middle pane if it makes sense. For this I need to calculate the width of the overflowing items box (which should be the sum of the items' width inside), and the container of it with the overflow: hidden attribute. (this should be the width of the browser window minus the left and right buttons).
Is there a way to calculate the length of something in js without counting all of it's childrens length manually and sum it up?
Is there a way to get the width of the browser window? Is there a way to get a callback when the window is resized? I need to correct the panes position if the window suddenly widens (and the items are in a position that should not be allowed)
Since the window's width can vary I need to calculate on the fly if I can scroll left or right.
Can you help me with the javascript?
UPDATE: I have a followup question for this one: Scroll a div vertically to a desired position using jQuery Please help me solve that one too.
Use white-space:nowrap on the item container and display:inline or display:inline-block to prevent the items from wrapping and to not need to calculate or set an explicit width.
Edit:: Here's a live working demo: http://jsfiddle.net/vhvzq/2/
HTML
<div class="hscroll">
<ol>
<li>...</li>
<li>...</li>
</ol>
<button class="left"><</button>
<button class="right">></button>
</div>
CSS
.hscroll { white-space:nowrap; position:relative }
.hscroll ol { overflow:hidden; margin:0; padding:0 }
.hscroll li { list-style-type:none; display:inline-block; vertical-align:middle }
.hscroll button { position:absolute; height:100%; top:0; width:2em }
.hscroll .left { left:0 }
.hscroll .right { right:0 }
JavaScript (using jQuery)
$('.hscroll').each(function(){
var $this = $(this);
var scroller = $this.find('ol')[0];
var timer,offset=15;
function scrollLeft(){ scroller.scrollLeft -= offset; }
function scrollRight(){ scroller.scrollLeft += offset; }
function clearTimer(){ clearInterval(timer); }
$this.find('.left').click(scrollLeft).mousedown(function(){
timer = setInterval(scrollLeft,20);
}).mouseup(clearTimer);
$this.find('.right').click(scrollRight).mousedown(function(){
timer = setInterval(scrollRight,20);
}).mouseup(clearTimer);
});
Thanks Phrogz for this part -- give the image container the white-space: nowrap; and display: inline-block;.
You can calculate the width without having to calculate the width of the children every time but you will need to calculate the width of the children once.
//global variables
var currentWidth = 0;
var slideDistance = 0;
var totalSize = 0;
var dispWidth = (winWidth / 2); //this should get you the middle of the page -- see below
var spacing = 6; //padding or margins around the image element
$(Document).Ready(function() {
$("#Gallery li").each(function () {
totalSize = totalSize + parseFloat($(this).children().attr("width"));// my images are wrapped in a list so I parse each li and get it's child
});
totalSpacing = (($("#Gallery li").siblings().length - 1) * spacing); //handles the margins between pictures
currentWidth = (parseFloat($("#Gallery li.pictureSelected").children().attr("width")) + spacing);
maxLeftScroll = (dispWidth - (totalSize + totalSpacing)); //determines how far left you can scroll
});
function NextImage() {
currentWidth = currentWidth + (parseFloat($("#Gallery li.pictureSelected").next().children().attr("width")) + spacing); //gets the current width plus the width of the next image plus spacing.
slideDistance = (dispWidth - currentWidth)
$("#Gallery").animate({ left: slideDistance }, 700);
}
There is a way to get the browser window with in javascript (jQuery example).
and there is a way to catch the resize event.
var winWidth = $(window).width()
if (winWidth == null) {
winWidth = 50;
}
$(window).resize(function () {
var winNewWidth = $(window).width();
if (winWidth != winNewWidth) {
window.clearTimeout(timerID);
timerID = window.setInterval(function () { resizeWindow(false); }, 100);
}
winWidth = winNewWidth;
});
On my gallery there's actually quite a bit more but this should get you pointed in the right direction.
You need to change your #items from
#items
{
float: left;
background: yellow;
width: 9000px;
}
to
#items {
background: yellow;
}
Then calculate the width very easily with jQuery
// #items width is calculated as the number of child .item elements multiplied by their outerWidth (width+padding+border)
$("#items").width(
$(".item").length * $(".item").outerWidth()
);
and simply declare click events for the #left and #right elements
$("#left").click(function() {
$("#middle").animate({
scrollLeft: "-=50px"
}, 'fast');
});
$("#right").click(function() {
$("#middle").animate({
scrollLeft: "+=50px"
}, 'fast');
});
jsFiddle link here
EDIT
I overlooked that detail about the varying image widths. Here is the correct way to calculate the total width
var totalWidth = 0;
$(".item").each(function(index, value) {
totalWidth += $(value).outerWidth();
});
$("#items").width(totalWidth);

Categories

Resources