Change div's width by a value in JS - javascript

How to change div's width by a certain value, like this:
someDiv.style.width += "100px";
It works when I want to set a value (i.e. width = "100px") but the problem is with += operator.

This would work for a vanilla javascript solution (since you didn't mention jquery):
var someDiv = document.getElementById("someDiv");
var w = 0;
if (typeof someDiv.clip !== "undefined") {
w = someDiv.clip.width;
} else {
if (someDiv.style.pixelWidth) {
w = someDiv.style.pixelWidth;
} else {
w = someDiv.offsetWidth;
}
}
someDiv.style.width = (w + 100) + "px";

<div id="test" style="height:100px"></div>
var elem=document.getElementById("test");
height=parseInt(elem.style.height);
height+=100;
height+="px"
console.log(height);
Try the following
http://jsfiddle.net/CME3Y/

That is because Javascript can't understand what "100px" + "100px" means, since those are string values.
I would do it like this using jQuery:
$(someDiv).width($(someDiv).width() + 100);

var currentwidth= $('#div').width();
$('#div').width(currentwidth +100);
http://jsfiddle.net/dolours/CME3Y/1/
Also you can use this https://stackoverflow.com/a/6179629/1479798

Related

How we can move CSS object from Right to Left using javascript?

Hi, In javascript we have option of finding offSetRight position of Element and can move it towards Left to Right side using setInterval method but i like to bring that object from right to left and i did not find any javascript method which i can use Here in my code , if you guys can take a look it would be great, also i like to mention i am new to Js so i hope people will go easy on me.
P.s - CSS and Jquery not allowed for animation.
var e = document.getElementById("aDiv");
var s = 1;
function myInterval() {
var eLeftPos = e.offsetLeft;
//console.log(e.offsetLeft);
e.style.left = (eLeftPos + s) + 'px';
//console.log(e.style.left);
var leftPos = (eLeftPos + s) >= 300
if (leftPos) {
function myInterval1() {
var eTopPos = e.offsetTop;
//console.log(e.offsetLeft);
e.style.top = (eTopPos + s) + 'px';
//console.log(e.style.top);
if ((eTopPos + s) >= 100){
clearInterval(internal1)
}
}
var internal1 = setInterval(myInterval1, 100);
}
if ((eLeftPos + s) >= 300){
clearInterval(internal)
}
}
var internal = setInterval(myInterval, 100);
Try Using CSS methods instead of Javascript. Try this:
CSS Animation from Left to Right
or this: How to animate sliding-in text form left to right

function doesn't execute on jquery document ready

I have a javascript function that resize and centers images based on the surrounding container size (that in turn depend on the window size). I use jquery as js framework. The function need to be executed after document load (on document ready) but also when and if the user changes size of the browser, ie I have the following running in the html-document:
$(document).ready(function(){
fixImageSizes();
});
$(window).resize(function() {
fixImageSizes();
});
But for some unknown reason the function is only executed when a user resizes the browser and not after loading. Can anyone please help with this?
(my function is below for knowledge...)
function fixImageSizes()
{
var cw = $('#imagecontainer').width();
var ch = $('#imagecontainer').height();
$('#imagecontainer img').each(function()
{
var iw = $(this).css('width');
var ih = $(this).css('height');
if (parseInt(iw) < parseInt(cw)) // image width < viewport
{
var newih = Math.ceil(parseInt(ih) * parseInt(cw) / parseInt(iw)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(newih)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(cw)/2) + 'px';
$(this).css({'width':cw,'height':newih,'margin-left':newimarginl,'margin-top':newimargint});
}
if (parseInt(ih) < parseInt(ch)) // image height < viewport
{
var newiw = Math.ceil(parseInt(iw) * parseInt(ch) / parseInt(ih)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(ch)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(newiw)/2) + 'px';
$(this).css({'width':newiw,'height':ch,'margin-left':newimarginl,'margin-top':newimargint});
}
if (parseInt(ih) > parseInt(ch) && parseInt(iw) > parseInt(cw)) // viewport smaller than image, shrink image
{
if (parseInt(ch) - parseInt(ih) > parseInt(cw) - parseInt(iw)) // difference is less on height
{
var newiw = Math.ceil(parseInt(iw) * parseInt(ch) / parseInt(ih)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(ch)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(newiw)/2) + 'px';
$(this).css({'width':newiw,'height':ch,'margin-left':newimarginl,'margin-top':newimargint});
}
else // difference less on width
{
var newih = Math.ceil(parseInt(ih) * parseInt(cw) / parseInt(iw)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(newih)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(cw)/2) + 'px';
$(this).css({'width':cw,'height':newih,'margin-left':newimarginl,'margin-top':newimargint});
}
}
});
You should use the load event instead of the ready event.
The ready event runs after the document has loaded, but before the images has loaded, so you won't have the correct size of all elements.
The function is probably executing (you can double-check with a simple alert), but the images you are "fixing" is probably not loaded yet. You can use the window.onload event or listen to the image load event like this:
var scale = function() {
// rescale
};
$('#imagecontainer img').each(function() {
this.complete ? scale.call(this) : $(this).load(scale);
});
Try this:
$(window).load(function (){
fixImageSizes();
});

onhover how to get the image width and height using jquery

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.

Appending Something on to Variable

I have the code
<script type="text/javascript">
var yourImg = document.getElementById('image');
if(yourImg && yourImg.style) {
yourImg.style.height = screen.availWidth;
yourImg.style.width = screen.availHeight;
}
</script>
And I need to append px to the end of the width and height.
Thanks in Advance,
Chase
Concatenation of strings (and other values) in javascript is made using the "+" (plus) character. In your code:
<script type="text/javascript">
var yourImg = document.getElementById('image');
if(yourImg && yourImg.style) {
yourImg.style.height = screen.availWidth;
yourImg.style.width = screen.availHeight;
var height = yourImg.style.height + 'px';
var width = yourImg.style.width + 'px';
}
</script>
You didn't really provide much information, but:
screen.availWidth + 'px';
screen.availHeight + 'px';
yourImg.style.height = screen.availWidth+'px';
yourImg.style.width = screen.availHeight+'px';

Font size auto adjust to fit

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;
}

Categories

Resources