Substract half of div width with js - javascript

I'm new using JS and I'm having troubles with a simple action:
First div is 50% width
I'm looking to subtract from its width the 50% of a Second div using JS.
Would be like:
a_div width = 50% - ( 50% width of b_div)
I've tried this but it's not working
$(document).ready(function(){
$("#h-prev").css({'width':($(".swiper-slide-prev").innerWidth())}).css('width:'-$(".swiper-slide-prev").width() * .50);
});

Get the parent width divided by 2 and subtract the other element width divided by 2
var $el = $("#h-prev"),
parentWidth = $el.parent().width(),
otherWidth = $(".swiper-slide-prev").width(),
newWidth =(parentWidth/2) - (otherWidth/2)
$el.width( newWidth );

I don't know exactly if this is what you are looking for, but I've written up this demo in plain javascript: https://jsfiddle.net/tubL1qxr/2/
var a = document.getElementById('a'), // element a
b = document.getElementById('b'), // element b
h = document.getElementById('h'); // button
h.addEventListener('click', changeSize);
function changeSize() {
a.style.width = ((window.innerWidth / 100 *50) - (b.offsetWidth /100*50)) + 'px';
}
You would quite obviously, have to modify it to fit your code.

This takes the first and the second divs width, then subtracts half of the second divs width from the first div's width (which is 50% initially).
Is this what you meant:
$(document).ready(function(){
var secondDivWidth = parseInt($('#second-div').css('width'));
var firstDivWidth = parseInt($('#first-div').css('width'));
$('#first-div').css('width', firstDivWidth - secondDivWidth/2);
// Example purposes only
console.log("Width before change (50%): " + firstDivWidth);
console.log("Width after change: " + $('#first-div').css('width'));
})
#first-div {
border: black solid 1px;
height: 100px;
width:50%;
}
#second-div {
border: red solid 1px;
height: 100px;
width: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="first-div">
</div>
<div id="second-div">
</div>

You have syntax errors:
jQuery css() functions works in 2 ways, accept object or 2 parameters:
1) css('attr', value)
2) css({'attr':value})
So you can correct this 'width:' and put this 'width': and put in {}
Result will be following:
$(document).ready(function() {
$("#h-prev").css({
'width': ($(".swiper-slide-prev").innerWidth())
}).css({'width':- $(".swiper-slide-prev").width() * .50});
});
In case of giving only one parametter you can use second option and code will be following
$(document).ready(function() {
$("#h-prev").css('width', ($(".swiper-slide-prev").innerWidth())).css('width', -$(".swiper-slide-prev").width() * .50);
});
So now syntax is correct, and if you will put here your code with snippet I will be able to help you with functionality.

Related

Detecting background image top margin with javascript

This is how I detect the top margin of a div and increase/decrease it:
var oldm = $("#bdi").css("margin-top").replace("px", "");
var addm = 1;
$("#bdi").css({
'margin-top': '-='+addm+'px'
})
But I need to do the same with background position.
detect the actual top position of a background image
increase/decrease the top margin of a background image
For example:
background-position: center 5px;
How do I detect "5px" and increase/decrease it?
Thanks
You can get it using background-position-y like this :
var bgPositionY = ($("#bdi").css('background-position-y'))
var addPos = 5;
$("#bdi").css({
'background-position-y': '-='+addPos+'px'
})
https://jsfiddle.net/IA7medd/aLkok1n4/
You don't need jQuery for this...
var el = document.getElementById('bdi'),
currentYPosition = getComputedStyle(el)['backgroundPositionY'],
increment = 1,
newYPosition = 'calc(' + currentYPosition + ' + ' + increment + 'px)';
// Set new backgroundPositionY
el.style.backgroundPositionY = newYPosition;
The use of calc() above ensures the value is properly incremented, even if a percentage position value is used.
As of jQuery 1.6, .css() accepts relative values similar to .animate(). Relative values are a string starting with += or -= to increment or decrement the current value. Link
For example like this
$("div").css("background-position-x", "+=10px");
$("div").css("background-position-Y", "-=10px");
If you want to do other operation on css value use this
$("div").css("background-position-x", function(index) {
return index * 10;
});
You can see demo at bottom
$("#increaseX").click(function(){
$("#image").css("background-position-x", "+=10px");
});
$("#decreaseX").click(function(){
$("#image").css("background-position-x", "-=10px");
});
$("#increaseY").click(function(){
$("#image").css("background-position-y", "+=10px");
});
$("#decreaseY").click(function(){
$("#image").css("background-position-y", "-=10px");
});
#image {
width: 100px;
height: 100px;
background-image: url("https://assets.servedby-buysellads.com/p/manage/asset/id/28536");
background-position: 0px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image"></div>
<button id="increaseX">increaseX</button>
<button id="decreaseX">decreaseX</button>
<br />
<button id="increaseY">increaseY</button>
<button id="decreaseY">decreaseY</button>
Firefox doesn't support background-position-x and background-position-y. If you want to do your target work in firefox, see jsfiddle
You can
If you're using jQuery, the simplest option is to use incremental notation inline:
$("#bdi").css('background-position-y', '+=5px');

Toggle class and change size on an element using jQuery

I am trying to have a div change its properties on a click function. Some of the properties I am changing with a call to toggleClass() which is fine and works great. However I also want to resize the div based on the size of the viewport. In order to have access to those numbers I am changing the width and height with jQuery. This command looks like this:
$('.box').click( function() {
$(this).toggleClass('box--grow', 0);
$(this).css('width', w * .9);
$(this).css('height', h * .9);
});
EDIT I want the height and width to go back to 100%.
I tried using the toggle class but that caused the entire div to disappear, and this solution doesn't work because when I click the div again the class is removed but the height is the same.
I am looking for a way to toggle this or to get the viewport width within the css. I tried both approaches but couldn't get anything to what I am looking for.
why not using CSS VH and VW values?
CSS:
.my90Class{
width: 90vw;
height: 90vh;
}
JS:
$('.box').click( function() {
$(this).toggleClass("my90Class");
});
You need to get the window size first, and then put everything into combined .ready() and .resize() functions, to make it responsive.
function myfunction() {
var w = $(window).width();
var h = $(window).height();
$('.box').click(function () {
if ($(this).hasClass('box--grow')) {
$(this).removeClass('box--grow');
$(this).css({
'width': '',
'height': ''
});
} else {
$(this).addClass('box--grow');
$(this).css({
'width': w * .9,
'height': h * .9
});
}
});
}
$(document).ready(myfunction);
$(window).on('resize', myfunction);
jsfiddle
You can check for the class with:
$(this).hasClass('box--grow')
Then to remove the class:
$(this).removeClass('box--grow');
And to add it back again:
$(this).addClass('box--grow');
The end would look like this save the original width and height before the event so you can add it back again:
var oldwidth = $('.box').css('width');
var oldheight = $('.box').css('height');
$('.box').click( function() {
if($(this).hasClass('box--grow')) {
$(this).removeClass('box--grow');
$('.box').css('width', oldwidth);
$('.box').css('height', oldheight);
} else {
$(this).addClass('box--grow');
}
});
untested but it would probably work

how to center and make various images sizes fit in a container

I'm using bxslider to have a carousel of images. The thing is though, the images it receives to display are of somewhat unpredictable sizes. The container size is 243x243. And we know that no image will have a side smaller than 243. So...I'd like to center the image in the container. And either zoom in until the shorter of the two dimensions (L vs W) fills the container at 243, and the longer dimension overflow is hidden.
For the images I'm working with, doing this will be perfect for getting the important details of the picture in the frame.
But I'm having trouble...
I've tried the following to center the picture in the frame:
jQuery(".bx-container").each(function() {
var img_w = jQuery(this).children("img").width();
var img_h = jQuery(this).children("img").height();
var pos_top = (img_h - containerHeight) / 2;
var pos_left = (img_w - containerWidth) / 2;
var pos_top = (243 - img_h) / 2;
var pos_left = (243 - img_w) / 2;
jQuery(this).children("img").css({
'top' : pos_top + 'px',
'left' : pos_left + 'px'
});
});
And I've tried this to position not square images into the frame:
jQuery(".bx-container").each(function(){
var refRatio = 1;
var imgH = jQuery(this).children("img").height();
var imgW = jQuery(this).children("img").width();
if ( (imgW/imgH) < refRatio ) {
jQuery(this).addClass("bx-portrait");
} else {
jQuery(this).addClass("bx-landscape");
}
});
});
I've messed with both scripts and the css but I just can't seem to get it work. It either centers but doesn't resize right. Or resizes but centers wrong. Or does both wrong.
Here's the jsfiddle: http://jsfiddle.net/vgJ9X/298/
Could someone help me out?
Thanks!
EDIT:
New jsfiddle...the portrait ones work right. The landscape images still squish. :(
http://jsfiddle.net/vgJ9X/307/
EDIT:
I THINK it has something to do with relatively positioned elements not being allowed to overlap. Trying to find a fix. If anyone knows, edit the last fiddle I posted.
jQuery(".bx-container img").each(function () {
var w = jQuery(this).width();
var h = jQuery(this).height();
if (w > h) $(this).addClass('bx-landscape');
else $(this).addClass('bx-portrait');
});
Check this Updated JSFiddle
Update
jQuery(".bx-container img").each(function () {
var w = jQuery(this).width();
var h = jQuery(this).height();
if (w > h){
$(this).addClass('bx-landscape');
var trans= -243/2;
$(this).css('-webkit-transform','translateZ('+trans+'px)');
}
else if(h > w){
$(this).addClass('bx-portrait');
var trans= -243/2;
$(this).css('-webkit-transform','translateY('+trans+'px)');
}
});
check this JSFiddle
Update of Update
Found the issue with landscape, the plugin is setting max-width:100%; overriding it with max-width:none; fixes the issue...
Update Of Updated Fiddle
Try this:
img{
position:relative;
height:100%;
width:300px;
}
Simple an clean.
Demo: http://jsfiddle.net/vgJ9X/302/
I did a couple things to your jsfiddle.
First I changed the order of your resize and center functions, so the resize comes first. This way, the smaller images get resized, then centered. I also uncommented the first portion of your code.
You also had a couple of errors in your css. There was an extra closing bracket after img style declaration. Your .bx-portrait img and .bx-landscape img declarations were set to 100%px;.
Update:
Change the css in your two .bx classes to:
.bx-portrait img {
height: 100%;
width: auto;
}
.bx-landscape img {
height: auto;
width: 100%;
}
And add a clearfix to your ul:
.bxslider:after {
content: '';
clear: both;
display: table;
padding: 0;
margin: 0;
}
The height is clipping because .bx-viewport has a set height of 243px but also has a 5px border, which makes the actual internal height 233px. You'll need to make the height 253px to account for the 10px of border. This is why they don't look centered vertically.
DEMO
Why don't you just use background images instead and center them. Here is a demo from your original code
http://jsfiddle.net/8y8df/
If you want to show the full size image, just remove the background-size:contain; from the css.

White space on right of page

How do I get rid of that undesired white border on the right of the page?
The website basically dynamically resizes images on a grid, here's a video: https://vine.co/v/h2wtnw6K3H0
CSS:
body {
height: 100%;
width: 100%;
margin: 0;
}
grid {
height: 100%;
width: 100%;
}
.gridImage {
vertical-align: bottom;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
margin-bottom: 0px;
}
JS:
function resize() {
console.log($(window).width());
var newBody = "";
for (var i = 0; i <= 100; i++) {
newBody += '<img class="gridImage" src="Images/image2.jpg" width="' + $(window).width() / Math.floor(($(window).width() / 100)) + 'px" height="' + $(window).width() / Math.floor(($(window).width() / 100)) + 'px">';
}
document.getElementById("grid").innerHTML = newBody;
}
If my margins are zero, why is this showing up? Anything I'm missing? Thanks.
Ridcully has covered what the problem is, but here’s a solution.
First you would need to calculate the desired width of each image. This is simply your current equation wrapped in Math.ceil().
var windowWidth = $(window).width() // A slight performance improvement, plus cleaner code
var maxImageWidth = <your value here>
var unroundedImageWidth = windowWidth / Math.floor(windowWidth / maxImageWidth)
var roundedImageWidth = Math.ceil(unroundedImageWidth)
Unless your images fit perfectly, this will make each row slightly wider than the window, causing the final image on each line to wrap to the next. To prevent this, you need to set the gridContainer’s width to that of each row.
$('.gridContainer').width(windowWidth * roundedImageWidth / unroundedImageWidth)
Everything should look good, except for one thing: the horizontal scrollbar. This is easily fixed, however. Add this to your CSS:
.gridContainer {
overflow-x: hidden;
}
This will hide both the scrollbar and the final few pixels on each line. Perfect! Well, not quite.
The problem with this method is that one image per row takes the hit (loses pixels) for all of the others. If you have small images and a lot of images per row, you could end up losing a significant portion of your final column.
To avoid this, you can round your image widths upwards and distribute the overflow amongst all images in the row. This is a little more complicated than the previous method, but it does give a better result.
There are three more numbers you need to calculate.
var imagesPerRow = windowWidth / unroundedImageWidth
var numOfRows = Math.ceil($('.gridContainer img').length / imagesPerRow)
var spillage = windowWidth / roundedImageWidth - windowWidth // Pixels we have to lose
Now it’s just a matter of distributing the spillage.
var i = 0 // Loop counter
while (spillage !== 0) {
// Set the width of all images in column i to the width of that column - 1
$('.gridContainer img:nth-child(' + imagesPerRow + 'n-' + (i+1) + ')')
.width($('.gridContainer img:nth-child(' + (i+1) + ')').width() - 1)
spillage--
i++
}
There should no longer be more than a single pixel difference between the widths of the images.
It's because of rounding errors. What you do is fill the grid with 100 scaled images, depending on the browser to wrap to a new line when the image doesn't fit in the current row any more.
Now imagine a width of 305 pixels. Your formula gives an image width of 100 for that, so you get 3 images in a row and the next one wraps to the next row, leaving 5 pixels blank at the right border.
i think you should also add padding:0; to body its missing from your code.
Try it and even better just make a jsfiddle then it would be easier to check for everyone.

Resize positioned background image

I have span, and it's styles are represented below. My problem is, it was designed to fill 60px*60px span. But now, I have to make it to fill another span with 50px*50px size. But it can't work with background position, because if i change the background-size, all position slips away. So is there any way (css or javascript hack) to resize an image or a block element with bacground-image after the image has been drawn? I want to avoid rewriting all background positions (I've got classes for each icons like ".entertainment").
<span class="icon icon2 entertainment"></span>
span.icon2 {
float: left;
width: 50px;
height: 50px;
margin: 5px 0 0 0;
}
#wrapper span.icon.entertainment {
background-position: -60px -360px;
}
#wrapper span.icon {
background: url(https://teeg.hu/image/icon.png);
}
Thanks for any help!
There is no pure css solution.
There is a js solution. Resize the background (background-size) as you did, then for each element move the position with the difference between sizes / 2 (in your case 5px).
You don't rewrite the classes, just iterate through elements.
Note: This might become an extensive operation, it is better to rewrite classes, even though that is what you want to avoid (40 is not so much... at most 30 min - testing included).
Ok, I've written some hack. I resized the background:
background-size: 100px 1550px;
and did it with jQuery:
$(function() {
$("span.icon2").each(function(index, value) {
var pos = $(this).css("background-position").split(' ');
var newPos = [];
newPos[0] = parseInt(pos[0].replace("px", "")) / 60 * 50;
newPos[1] = parseInt(pos[1].replace("px", "")) / 60 * 50;
$(this).css("background-position", newPos[0] + "px " + newPos[1] + "px");
});
});

Categories