I have some code that allows me to change the img src when I've scrolled from top < 120 px. But I need to change the image to another one when the browser is resized too.
So I should get, 1 image when I scroll down 120 px, 1 image if I already scrolled down 120px but I reduced size of browser to 850 pixels,
1 image if I'm at full top of browser, and another image if I reduce size of browser.
So far I can only change img src if I scroll 120px down, but how can I solve the browser size at the same time?
$(window).on('scroll', function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > 120) {
$('#logo').attr('src', 'http://www.kubographics.com/adiacens/images/logo1-black.svg');
$('#logo').css('margin-top', '10px');
}
else {
('#logo').attr('src', '');
$('#logo').css('margin-top', '0px');
}
});
Thanks for your help!
To change the img use css media query
#logo {
background: url("http://www.kubographics.com/adiacens/images/logo1-black.svg")
}
#media (max-width: 850px) {
background: url("http://www.kubographics.com/adiacens/images/logo2-black.svg")
}
Related
When scrolling horizontally, the sidebar overlaps the other column. I am using jQuery + CSS to achieve this. How can I prevent this overlapping?
Before user reaches div container:
http://prnt.sc/b9j4t6
When user reaches div container (how it should always look):
http://prntscr.com/b9j7mz
Overlap Issue:
http://prnt.sc/b9j56m
Code:
var element = $('.price-container');
var baseTop = element.offset().top;
$(window).scroll(function () {
var top = $(this).scrollTop();
if (top >= baseTop)
element.css({"position": "fixed", "top": "10px"});
else
element.css({"position": "", "top": ""});
});
The reason the left container is overlapping the right container is because you are setting it to be fixed. This takes the element out of the normal flow of the page.
If you dont want it to happen you can either set up within your css a media query to say if your page is smaller than x position: static;
// change max-width: 480px to suit your screen size
#media screen and (max-width: 480px) {
.price-container { position: static !important; }
}
Or in your javascript
var top = $(this).scrollTop(),
width = $(window).width();
if (top >= baseTop && width >= [the point you want to break] ) {
element.css({"position": "fixed", "top": "10px"});
}
I have a 240x240px div which contains a fading slideshow of images differing in sizes. I have each image set to a height: 240px with the width being automatic in proportion to its height. Some images are taller than they are wide (in proportion) so I center them inside the div using position: relative; margin: 0 auto This works well except for images which overflow the 240px div. How could I go about centering images inside the div which overflow? I tried this (jQuery) but it doesn't work for some reason I'm sure I can't figure out:
if( $("div img").width() > 240 ) {
$(this).css("margin-left", rv);
var rv = -1 * ($(this).width() / 4) + "px";
}
The logic being, if the image expands the div in width, then shift it to the left by rvpx, rv being 1/4 of the image's width (as 1/2 would clip the image in half on the left, so 1/2 of 1/2 effectually centering it?) My first guess would be that I can't reference $(this) as I am trying to, though I have no idea.
I know I could go and add individual inline CSS styles but that's messy and mundane. I'd rather have a script which can automatically calculate the center of the image then move it accordingly. Any ideas?
I'd recommend something like this:
div.center-img { background:url('/path/img.jpg') center center no-repeat; }
But your question would be answered with something like this:
$('div img').each(function() {
if( this.width > 240 )
$(this).css("margin-left", ((this.width - 240) / -2) + "px");
});
You can use CSS only:
LIVE DEMO
.imgHolder{
border:1px solid #000;
width:240px;
height:240px;
line-height:240px; /* same as element height */
font-size:0; /* to perfectly vertical align middle the image */
text-align:center; /* to horizontally align middle the image */
}
.imgHolder > img{
max-width:100%;
max-height:100%;
vertical-align:middle;
}
Iterate over the images and when they have loaded get the image width and the parent element width, compare the width, and if the image is wider than the parent get half of the difference and subtract that from the left margin to center the image horizontally.
$("div.centered img").each(function(_,el) {
var img = new Image(),
parent = $(el).parent();
img.onload = function() {
var ma = this.width - $(parent).width();
if ( ma > 0 ) {
$(el).css('margin-left', ((ma/2) * -1));
}
}
img.src = this.src;
if (img.complete) img.onload();
});
FIDDLE
I need a <img> to have the smallest possible size without leaving any blank spaces inside a div and it needs to be centralized horizontally and vertically. The size of the image is variable.
So here is an example so you can understand it better:
http://jsfiddle.net/q2c9D/
More info: much like Mikel Ward did, I need the images to fill up the div, so that the background of it is not visible. I made the div background black so it was easier to tell that it is not filling up the div. But I need the images to be centered and to be the smallest size possible without being distorted while filling up the div.
Here is my go
I would set the width to 100%, and remove the height property altogether. This will prevent the image from being distorted
img{
width: 100%;
}
To center the element, I would use this plugin. It makes you do no work, other than to call the function
$("img").center()
Try adding min-width: 100% to the img. Here's an example. It may stretch the picture a little but at the size it is, may not be too noticeable. :)
This will center the image on the page:
img{
margin: 0 auto;
position: relative;
display: block;
}
Just wrap the images in a <div> to position them somewhere on the page.
The way i do it is set the width or height, but only 1 as 100%.
<img width="100%" src=""/>
So I was able to get it working the way I wanted using jQuery. With the following code:
function centerimg(){
$('img').each(function(){
var imgwidth = $(this).width();
var imgheight = $(this).height();
if (imgwidth > imgheight) {
$(this).css({
"height": "100%",
"width": "auto"
});
imgwidth = $(this).width();
$(this).css("margin-left", -.5 * imgwidth + 50 + "px");
} else if (imgheight > imgwidth) {
$(this).css({
"width": "100%",
"height": "auto"
});
imgheight = $(this).height();
$(this).css("margin-top", -.5 * imgheight + 50 + "px");
} else {
$(this).css({
"height": "100%",
"width": "100%"
})
}
})
};
window.onload = centerimg;<code>
The code gets the width and height of the image, so if the image is wider or taller it will properly set the smaller dimension to 100% and the larger one to auto. After that it gets the value of that last one again (since it was re sized with auto) and centers it. Also, if the image is a square it just sets both to 100%.
This way the image will ALWAYS fill up the div and be centered.
Thanks all. Hope this code helps others.
Is there a way to reliably tell a browser's viewport width that includes the scrollbar, but not the rest of browser window)?
None of the properties listed here tell me the width of the screen INCLUDING the scrollbar (if present)
I figured out how to accurately get the viewport width WITH the scrollbar using some code from: http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript
Put this inside your $(document).ready(function()
$(document).ready(function(){
$(window).on("resize", function(){
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
});
// Get the correct window sizes with these declarations
windowHeight = viewport().height;
windowWidth = viewport().width;
});
What it Does:
When your page is 'ready' or is resized, the function calculates the correct window height and width (including scrollbar).
I assume you want to know the viewport width with scrollbar included, because the screen it self does not have a scrollbar. In fact the Screen width and heigth will be the computer screen resolution itself, so I'm not sure what you mean with screen width with the scroll bar.
The viewport however, the area where only the page (and scroll bars) is presented to the user, meaning, no browser menus, no bookmarks or whatever, only the page rendered, is where such scroll bar may be present.
Assuming you want that, you can measure the client browser viewport size while taking into account the size of the scroll bars this way.
First don't forget to set you body tag to be 100% width and height just to make sure the measurement is accurate.
body {
width: 100%;
// if you wish to also measure the height don't forget to also set it to 100% just like this one.
}
Afterwards you can measure the width at will.
Sample
// First you forcibly request the scroll bars to be shown regardless if you they will be needed or not.
$('body').css('overflow', 'scroll');
// Viewport width with scroll bar.
var widthWithScrollBars = $(window).width();
// Now if you wish to know how many pixels the scroll bar actually has
// Set the overflow css property to forcibly hide the scroll bar.
$('body').css('overflow', 'hidden');
// Viewport width without scroll bar.
var widthNoScrollBars = $(window).width();
// Scroll bar size for this particular client browser
var scrollbarWidth = widthWithScrollBars - widthNoScrollBars;
// Set the overflow css property back to whatever value it had before running this code. (default is auto)
$('body').css('overflow', 'auto');
Hope it helps.
As long as body is 100%, document.body.scrollWidth will work.
Demo: http://jsfiddle.net/ThinkingStiff/5j3bY/
HTML:
<div id="widths"></div>
CSS:
body, html
{
margin: 0;
padding: 0;
width: 100%;
}
div
{
height: 1500px;
}
Script:
var widths = 'viewport width (body.scrollWidth): '
+ document.body.scrollWidth + '<br />'
+ 'window.innerWidth: ' + window.innerWidth + '<br />';
document.getElementById( 'widths' ).innerHTML = widths;
I put a tall div in the demo to force a scroll bar.
Currently the new vw and vh css3 properties will show full size including scrollbar.
body {
width:100vw;
height:100vh;
}
There is some discussion online if this is a bug or not.
there is nothing after scrollbar so "rest of the window" is what?
But yes one way to do it is make another wrapper div in body where everything goes and body has overflow:none; height:100%; width:100%; on it, wrapper div also also has 100% width and height. and overflow to scroll. SO NOW...the width of wrapper would be the width of viewport
See Example: http://jsfiddle.net/techsin/8fvne9fz/
html,body {
height: 100%;
overflow: hidden;
}
.wrapper {
width: 100%;
height: 100%;
overflow: auto;
}
With jQuery you can calculate the browser's scrollbar width by getting the width difference when overflow: hidden is set and overflow: scroll is set.
The difference in width will be the size of the scrollbar.
Here is a simple example that shows how you could do this.
You can get the window width with scrollbar , that way:
function scrollbar_width() {
if (jQuery('body').height() > jQuery(window).height()) {
/* Modified from: http://jdsharp.us/jQuery/minute/calculate-scrollbar-width.php */
var calculation_content = jQuery('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
jQuery('body').append(calculation_content);
var width_one = jQuery('div', calculation_content).innerWidth();
calculation_content.css('overflow-y', 'scroll');
var width_two = jQuery('div', calculation_content).innerWidth();
jQuery(calculation_content).remove();
return (width_one - width_two);
}
return 0;
}
Check out vw: http://dev.w3.org/csswg/css-values/#viewport-relative-lengths
body {
width: 100vw;
}
http://caniuse.com/#search=vw
This is my solution for removing the 'scrollbar shadow', because scrollWidth didn't work for me:
canvas.width = element.offsetWidth;
canvas.height = element.offsetHeight;
canvas.width = element.offsetWidth;
canvas.height = element.offsetHeight;
It's easy, but it works. Make sure to add a comment explaining why you assign the same value twice :)
So I am trying to insert an image to a page with JavaScript with 50% of its width and 50% of its height.
I do this:
someElement.html('<img src="/path/to/img.jpg" alt="" class="sImg" />');
The sImg class is defined in stylesheet like this:
.sImg{
border: 0;
width: 50%;
height: 50%;
}
Yet the image appears fullsize.
I have also checked via Firebug and the image has width and height both at 50%.
First of all, if you're setting a width and height, you should also include display: block; since inline elements don't generally enjoy being given a set height.
But more importantly, when you express a width (or height) as a percentage, that's a percentage of the parent element, so if the parent is 1000px wide, the image will be 500px wide (regardless of what size the actual image file is).
If you're using JavaScript to determine the current image size and change it, just express the new size in px instead of %.
The CSS you've got means that the width and height should be computed as half the size of the parent container, not the image itself.
What you can do is something like this: create an Image object and give it an "onload" handler. The handler can get reliable size information (because the image will have been loaded), and can then add the image element with the proper size.
var img = new Image();
img.onload = function() {
$(someElement).empty().append($('<img/>', {
src: img.src,
alt: '',
'class': 'sImg',
css: { width: Math.floor(img.width / 2) + 'px', height: Math.floor(img.height / 2) + 'px', display: 'inline-block' } // display should be set as you need it
});
};
img.src = yourUrl;
edit — the eerily knowledgeable Šime Vidas points out that setting the "width" or "height" attribute should make the right thing happen, with the size being reduced appropriately to maintain the aspect ratio.
Does the parent container have a height/width? it maybe that the browser does not know what 50% of x is and what 50% of y is. but if it knew what x and y were then it could apply it. Try
var myWidth = $('.sImg').width(),
myHeight = $('.sImg').height();
myWidth = myWidth / 2;
myHeight = myHeight / 2;
$('.sImg').attr('width', myWidth + 'px').attr('height', myHeight + 'px');
http://api.jquery.com/width/
http://api.jquery.com/height/