I'm trying to set, with javascript, the width of one div to the width of another. In my case, the second div was cloned from the first.
The issue I'm running into is related to padding, and how style.width is defined differently from clientWidth/offsetWidth/scrollWidth. In my example below, I have two divs defined the same except with different widths. When the button is pressed, I'm trying to set the width of the smaller one to the bigger one - but the outcome is that it gets the width of the bigger one PLUS the padding (an extra 20px).
Is there a way to change the line:
two.style.width = one.clientWidth + 'px';
to make the two divs equal in width?
function setWidth() {
var one = document.getElementById("one");
var two = document.getElementById("two");
two.style.width = one.clientWidth + 'px';
}
.outer {
background: red;
padding: 10px;
}
.inner {
background: green;
height: 10px;
}
#one {
width: 100px;
}
#two {
width:50px;
}
<div id=one class=outer><div class=inner></div></div>
<br>
<div id=two class=outer><div class=inner></div></div>
<button onclick="setWidth()">SET WIDTH</button>
You can use getComputedStyle:
function setWidth() {
var one = document.getElementById("one");
var two = document.getElementById("two");
style = window.getComputedStyle(one);
wdt = style.getPropertyValue('width');
two.style.width = wdt;
}
Here's a fiddle
You should make use of .offsetWidth. They belong to the element, not .style.
function setWidth() {
var w=document.getElementById('one').offsetWidth
document.getElementById('two').setAttribute("style","width:"+w+"px");
}
The width isn't taking into account the padding. You'll still need to subtract it. Something like this should work:
function setWidth() {
var one = document.getElementById("one");
var two = document.getElementById("two");
two.style.width = one.offsetWidth + 'px';
//update the width again, subtracting the difference between the first div and the second (which includes padding)
two.style.width = (two.offsetWidth-((two.offsetWidth - one.offsetWidth)*2)) + 'px';
}
You can see it working here: https://jsfiddle.net/igor_9000/55d1pfak/1/
For what its worth, jQuery handles this a little easier and gets the elements width including padding/borders. That may be another option for you.
Hope that helps!
You need to take one's padding into consideration.
function setWidth() {
var one = document.getElementById("one");
var two = document.getElementById("two");
var leftPadding = window.getComputedStyle(one, null).getPropertyValue('padding-left');
var width = window.getComputedStyle(one, null).getPropertyValue('width');
two.style.width = width;
two.style.padding = leftPadding;
}
Here's a JSFiddle.
My code will find the largest width for all elements using class 'js-equal-width' and it will set all of them to the same width.
$(function() {
const extraWidth = 50
var maxWidth = 0
$('.js-equal-width').each(function() {
maxWidth = maxWidth > $(this).width() ? maxWidth : $(this).width()
})
$('.js-equal-width').each(function() {
$(this).width(maxWidth + extraWidth)
})
})
You can do it by using 'js-equal-width'
<div style="width: 300px;">
<span class="js-equal-width">Midterm Examination</span>
<span class="js-equal-width">Final Examination</span>
</div>
Related
I want to cut the margin-left of a div container in half under a certain window width (mobile).
I've tried this with parseInt, .css and store it temporarly in a variable. Then cut it in half and use .replace.
if ($(window).width() <= 590) {
let oldmargin = parseInt($("#div").css("marginLeft"));
let newmargin = oldmargin/2;
$("#div").css("marginLeft").replace('rem', newmargin);
}
Unfortunately the code is not working.
To set a new value of margin-left, try with $("#div").css("margin-left",newmargin);
To GET a value using .css() = $("#div").css("margin-left")
To SET a value using .css() = $("#div").css("margin-left",newmargin)
$('.div').each(function() {
var oldmargin = parseInt($(this).css("marginLeft"));
var newmargin = oldmargin / 2;
$(this).css("marginLeft", newmargin);
});
Demo
$('.div').each(function() {
var oldmargin = parseInt($(this).css("marginLeft"));
var newmargin = oldmargin / 2;
$(this).css("marginLeft", newmargin);
});
.div {
margin-left: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div">#div</div>
<div class="div">#div</div>
I am trying to know if I could predict the number of strings including white-space that can be inserted inside a div of fixed width and fixed font-size programatically.. I have a divs of diferent width in to which I add names dynamically.. so the width varies based on the some density measures of that name..
I know I can use the css methods like
"white-space", "nowrap"
"overflow", "hidden"
"text-overflow", "ellipsis"
but I wanna know if I do it using javascript or jquery?
Yes you can do it programmatically. Check this
var wid = $("div").width();
var allowedChars = parseInt(wid/getCharWidth('Courier New', '10px'));
var div = $("div");
for(var i = allowedChars; i > 0; i--) {
$(div).append("a");
}
function getCharWidth(fontFamily, fontSize) {
var div = document.createElement("div");
div.style.position = "absolute";
div.style.visibility = "hidden";
div.style.fontFamily = fontFamily;
div.style.fontSize = fontSize;
div.innerHTML = "S";
document.body.appendChild(div);
var width = div.offsetWidth;
document.body.removeChild(div);
return(width);
}
Also check this link for more information.
Cheers!!!
I am displaying in my webpage a number of images within a div the div and images are created dynamically with a looping.
I need to get the width and height of the each image by using the jquery without using id like this
document.getElementById('Image/div id');
because there will a lot of images dynamically created by the loop depend upon the conditions
so, is there any way to get the height and width of the image when user hover/click the image
I struck with this for a long and been here finally hopes i get a solution
you can use jQuery on() to attach a handler to the nearest common parent container. that way, you can at least control which subset of images you want this function to take effect.
$('#container').on('mouseover','img',function(){
var width = $(this).width();
var height = $(this).height();
});
like:
<div>
<img> //will not affect this one since it's not under "#container"
</div>
<div id="container">
<img> //the handler affects this one
<div>
<img> //the handler also affects this one
</div>
</div>
I'd suggest, if you want to show this information on the page:
$('img').hover(
function(){
var h = $(this).height(),
w = $(this).width();
$('<div />').insertAfter($(this)).text('height: ' + h + '; width: ' + w +'.');
},
function(){
$(this).next('div').remove();
});
JS Fiddle demo.
Almost pointless edit to make it a little bit prettier by reducing the calls to $(this) and coupling it to some CSS:
$('img').hover(
function(){
var that = $(this),
h = that.height(),
w = that.width();
$('<div />')
.css('width',w)
.text('height: ' + h + '; width: ' + w +'.')
.insertAfter(that);
},
function(){
$(this).next('div').remove();
});
CSS:
div {
display: block;
position: relative;
}
div > div {
position: absolute;
top: 0;
left: 0;
color: #f90;
background-color: #000;
background-color: rgba(0,0,0,0.6);
}
JS Fiddle demo.
Edited because jQuery's not really necessary for this effect (albeit it does simplify the implementation), so: a plain JavaScript alternative:
var img = document.getElementsByTagName('img');
for (var i=0,len=img.length;i<len;i++){
img[i].onmouseover = function(){
var that = this,
h = that.offsetHeight,
w = that.offsetWidth,
p = that.parentNode,
d = document.createElement('div');
d.style.width = w + 'px';
d.textContent = 'Width: ' + w + '; height: ' + h + '.';
p.appendChild(d);
};
img[i].onmouseout = function(){
var that = this;
that.parentNode.removeChild(that.nextSibling);
};
}
JS Fiddle demo.
Final edit (I think), because I couldn't remember the compatibility for node.textContent, I thought this amendment might aid compatibility with lower versions of IE (using document.createTextNode() instead of relying on node.textContent/node.innerText and so on...):
var img = document.getElementsByTagName('img');
for (var i=0,len=img.length;i<len;i++){
img[i].onmouseover = function(){
var that = this,
h = that.offsetHeight,
w = that.offsetWidth,
p = that.parentNode,
d = document.createElement('div'),
text = document.createTextNode('Width: ' + w + '; height: ' + h + '.');
d.appendChild(text);
d.style.width = w + 'px';
p.appendChild(d);
};
img[i].onmouseout = function(){
var that = this;
that.parentNode.removeChild(that.nextSibling);
};
}
JS Fiddle demo.
While I don't have IE 7, or lower, the above does work in IE 8 at least. If anyone has comments about functionality in IE 6 or 7 I'd be interested..!
References:
'Plain' JavaScript:
document.createElement.
document.createTextNode().
element.offsetHeight.
element.offsetWidth.
element.style.
node.appendChild.
node.parentNode.
node.removeChild.
node.textContent.
jQuery:
height().
hover().
insertAfter().
next().
remove().
text().
width().
Does this solve your issue?
$('img').hover(function() {
console.log($(this).width());
console.log($(this).height());
});
Use $(this) to refer to the image being hovered.
$("#div_id").hover(function(){
alert("H:" + $(this).height() + " W:" + $(this).width() );
});
$(".img").mouseover(function() {
var $div = $(this);
var $item = $div.find("img");
var width = $item.width();
var height = $item.height();
}
try this.
Does anybody know of a script that will let me diplay image results in the way that Google Image Search does (image grid view) with hover to enlarge and details? Something that I can just "plug-and-play" so to speak.
Have a look at Masonry http://masonry.desandro.com/
First, you need to put all images inside a container element:
<div class="parent">
<img src="">
<img src="">
<img src="">
</div>
Then you need to make sure that the images are displayed in one line. This can be done by e.g. float: left. You should also set vertical-align to remove the small gap underneath each image:
img {
float: left;
vertical-align: top;
}
Finally you need some JavaScript to loop through all images and calculate the ideal rowHeight based on their dimensions. The only thing you need to tell this algorithm is the maximum row height that you want (rowMaxHeight)
// Since we need to get the image width and height, this code should run after the images are loaded
var elContainer = document.querySelector('.parent');
var elItems = document.querySelector('.parent img');
var rowMaxHeight = 250; // maximum row height
var rowMaxWidth = elContainer.clientWidth;
var rowWidth = 0;
var rowRatio = 0;
var rowHeight = 0;
var rowFirstItem = 0;
var rowIsLast = false;
var itemWidth = 0;
var itemHeight = 0;
// Make grid
for (var i = 0; i < elItems.length; i++) {
itemWidth = elItems[i].clientWidth;
itemHeight = elItems[i].clientHeight;
rowWidth += itemWidth;
rowIsLast = i === elItems.length - 1;
// Check if current item is last item in row
if (rowWidth + rowGutterWidth >= gridWidth || rowIsLast) {
rowRatio = Math.min(rowMaxWidth / rowWidth, 1);
rowHeight = Math.floor(rowRatio * rowMaxHeight);
// Now that we know the perfect row height, we just
// have to loop through all items in the row and set
// width and height
for (var x = rowFirstItem; x <= i; x++) {
elItems[i].style.width = Math.floor(rowRatio * itemWidth * (rowMaxHeight/itemHeight)) + 'px';
elItems[i].style.height = rowHeight + 'px';
}
// Reset row variables for next row
rowWidth = 0;
rowFirstItem = i + 1;
}
}
Note that this code is not tested and a very simplified version of what this vanilla JavaScript plugin does: https://fld-grd.js.org
Two solutions that I have found so far.
tutorial blog
jsfiddle
$(function() {
$(window).on('resize', function() {
$('.openEntry').remove();
$('.entry').hide();
var startPosX = $('.preview:first').position().left;
console.log(startPosX);
$('.entry, .preview').removeClass("first last");
$('.entry').each(function() {
if ($(this).prev('.preview').position().left == startPosX) {
$(this).prev('.preview').addClass("first");
$(this).prevAll('.entry:first').addClass("last");
}
});
$('.entry:last').addClass("last");
});
$(window).trigger('resize');
$('.trigger').click(function() {
$('.openEntry').slideUp(800);
var preview = $(this).closest('.preview');
preview.next('.entry').clone().addClass('openEntry').insertAfter(preview.nextAll('.last:first')).slideDown(800);
});
$('body').on('click', '.close', function() {
$('.openEntry').slideUp(800).remove();
});
})
codrops actually puts the photo enlargement/details inline instead of as a modal overlay:
http://tympanus.net/codrops/2013/03/19/thumbnail-grid-with-expanding-preview/
This might be what you are looking for... http://www.gethifi.com/demos/jphotogrid
Have a look at the gPop plugin
DEMO
Download in Github
Check out this jQuery Plugin: https://github.com/brunjo/rowGrid.js
It places images like on the Google image search.
Simply just repeat your images like this:
<img style="float: left; height: 12em; margin-right: 1%; margin-bottom: 0.5em;border:1px solid lightgray" src="ImgSrc " />
I'm trying to do what the title says. I've seen that font-size can be a percentage. So my guess was that font-size: 100%; would do it, but no.
Here is an example: http://jsfiddle.net/xVB3t/
Can I get some help please?
(If is necesary to do it programatically with js there is no problem)
This question might help you out but I warn you though this solves it through jQuery:
Auto-size dynamic text to fill fixed size container
Good luck.
The OP of that question made a plugin, here is the link to it (& download)
BTW I'm suggesting jQuery because as Gaby pointed out this can't be done though CSS only and you said you were willing to use js...
Can't be done with CSS.
100% is in relation to the computed font-size of the parent element.
reference: http://www.w3.org/TR/CSS2/fonts.html#font-size-props
For a jQuery solution look at Auto-size dynamic text to fill fixed size container
I was looking into this for work and I liked tnt-rox's answer, but I couldn't help but notice that it had some extra overhead that could be cut out.
document.body.setScaledFont = function(){
this.style.fontSize = (this.offsetWidth*0.35)+'%';
return this;
}
document.body.setScaledFont();
Cutting out the overhead makes it run a little bit quicker if you add it to an onresize event.
If you are only looking to have the font inside a specific element set to resize to fit, you could also do something like the following
window.onload = function(){
var scaledFont = function(el){
if(el.style !== undefined){
el.style.fontSize = (el.offsetWidth*0.35)+'%';
}
return el;
}
navs = document.querySelectorAll('.container>nav'),
i;
window.onresize = function(){
for(i in navs){
scaledFont(navs[i]);
}
};
window.onresize();
};
I just noticed nicolaas' answer also had some extra overhead. I've cleaned it up a bit. From a performance perspective, I'm not really a fan of using a while loop and slowly moving down the size until you find one that fits.
function setPageHeaderFontSize(selector) {
var $ = jQuery;
$(selector).each(function(i, el) {
var text = $(el).text();
if(text.length) {
var span = $("<span>").css({
visibility: 'hidden',
width: '100%',
position: 'absolute',
'line-height': '300px',
top: 0,
left: 0,
overflow: 'visible',
display: 'table-cell'
}).text(text),
height = 301,
fontSize = 200;
$(el).append(span);
while(height > 300 && fontSize > 10) {
height = span.css("font-size", fontSize).height();
fontSize--;
}
span.remove();
$(el).css("font-size", fontSize+"px");
}
});
}
setPageHeaderFontSize("#MyDiv");
And here is an example of my earlier code using jquery.
$(function(){
var scaledFont = function(el){
if(el.style !== undefined){
el.style.fontSize = (el.offsetWidth*0.35)+'%';
}
return el;
};
$(window).resize(function(){
$('.container>nav').each(scaledFont);
}).resize();
});
A bit late but this is how I approach this problem:
document.body.setScaledFont = function() {
var f = 0.35, s = this.offsetWidth, fs = s * f;
this.style.fontSize = fs + '%';
return this
}
document.body.setScaledFont();
The base document font is now set.
For the rest of your elements in the dom set font sizes as % or em and they will scale proportionately.
here I have a mootools solution:
Element.implement("fitText", function() {
var e = this.getParent();
var maxWidth = e.getSize().x;
var maxHeight = e.getSize().y;
console.log(maxWidth);
var sizeX = this.getSize().x;
var sizeY = this.getSize().y;
if (sizeY <= maxHeight && sizeX <= maxWidth)
return;
var fontSize = this.getStyle("font-size").toInt();
while( (sizeX > maxWidth || sizeY > maxHeight) && fontSize > 4 ) {
fontSize -= .5;
this.setStyle("font-size", fontSize + "px");
sizeX = this.getSize().x;
sizeY = this.getSize().y;
}
return this;
});
$$("span").fitText();
Here is another jQuery solution ...
/**
* Resizes page header font-size for the text to fit.
* basically we add a hidden span into the header,
* put the text into it and then keep reducing the super large font-size
* for as long as the height of the span exceeds the super
* tall line-height set for the test (indicating there is more than one line needed
* to show the text).
*/
function setPageHeaderFontSize(selectorString) {
jQuery(selectorString).each(
function(i, el) {
var text = jQuery(el).text();
var length = text.length;
if(length) {
var id = "TestToSeeLengthOfElement_" + i;
jQuery(el).append("<span style='visibility: hidden; width: 100%; position: absolute; line-height: 300px; top: 0; left: 0; overflow: visible; display: table-cell;' id='"+id+"'>"+text+"</span>");
var innerEl = jQuery("#"+id);
var height = 301;
var fontSize = 200;
while(height > 300 && fontSize > 10) {
height = jQuery(innerEl).css("font-size", fontSize).height();
fontSize--;
}
jQuery(innerEl).remove();
jQuery(el).css("font-size", fontSize+"px");
}
}
);
}
//you can run it like this... using any jQuery enabled selector string (e.g. h1.pageHeaders works fine).
setPageHeaderFontSize("#MyDiv");
Here's a way to find the height of the text that you are using.
It's simple and only uses javascript. You can use this to adjust your text relative to the height you want.
function getTextHeight(text, fontSize) {
var numberOfLines = 0;
var STL = text;
for(var i = 0; i < STL.length; i++){
if(STL[i] === '<'){
try{
if(STL[i + 1] === 'b' && STL[i + 2] === 'r' && STL[i + 3] === '>'){
numberOfLines++;
}
}
catch(err){
break;
}
}
return (numberOfLines + 1) * fontSize;
}