change margin-left with JS - javascript

I want a dynamical margin-left on a given div.
I tried this code :
window.onload = function()
{
var pageWidth = window.innerWidth;
var size = (pageWidth - 200 ) / 2;
$('#search').css('margin-Left', size));
alert(size);
};
which doesn't work (the alert is here just for test purpose), the problem is coming from the ligne $('#search').css('margin-Left', size)); but I can't find out where...
I've tried with a lowercase l on margin-left and didn't work.

Would the following work for you?
document.getElementById("search").style.marginLeft = size + "px";

You need to specify the type of unit you want to use.
$('#search').css('margin-left', size + 'px');

Try using marginLeft, without the hypen.
jQuery.css() documentation: http://api.jquery.com/css/

JAVASCRIPT
$(document).ready(function(e){
alert('test');
var pageWidth = parseInt($(window).innerWidth());
alert(pageWidth);
var size = (pageWidth - 200 ) / 2;
$('#search').css('margin-left', size);
alert(size);
})
HTML
<div id = 'search'></div>
CSS
#search
{
height:100px;
width:100px;
background-color:#F00;
}
FIDDLE LINK

Related

Add to width using setInterval

I am trying to add to the width of the element everytime the setInterval function is invoked
function setProgress(){
var bar = document.getElementById('progress-bar');
var width = 20;
bar.style.width += width + 'px';
//console.log(bar.style.width);
}
window.onload = function(){
setInterval(setProgress, 10);
}
I tried using parseInt(), but everytime I console.log() to the window i see the same width. My end goal is for the width to increase by 20
You need to remove px part from width style and then cast string to number before incrementing it:
function setProgress(){
var bar = document.getElementById('progress-bar');
var width = 20;
bar.style.width = Number(bar.style.width.replace('px', '')) + width + 'px';
//console.log(bar.style.width);
}
Make width a global var, like shown below:
var width = 0;
function setProgress(){
var bar = document.getElementById('progress-bar');
width+= 20;
bar.style.width += width + 'px';
//console.log(bar.style.width);
}
window.onload = function(){setInterval(setProgress, 10);}
Also, you should specify the max width to prevent the progress bar moving outside the working area (for example, modifying the increment line: if(width<500) {width+= 20;} else {return;}).
Alternatively, you can use your original solution by adding couple more statements, namely: removing the "px" unit from style property bar.style.width, then parsing it (converting to Number), then incrementing it and then adding "px" (otherwise, "+" operator will cause a concatenation of strings with output like: 20px20px, 20px20px20px, etc). Such alternative solution will slow down the process and put additional load on CPU (thus, it's not recommended).
Hope this may help. Best regards,
The problem is that width returns a string with units.
Instead, consider storing the number of pixels in a variable:
var bar = document.getElementById('progress-bar'),
width = parseFloat(getComputedStyle(bar).width);
setInterval(function() {
width += 20;
bar.style.width = width + 'px';
}, 10);
var bar = document.getElementById('progress-bar'),
width = parseFloat(getComputedStyle(bar).width);
setInterval(function() {
width += 20;
bar.style.width = width + 'px';
}, 200);
#progress-bar {
background: #0f0;
display: inline-block;
}
<div id='progress-bar'>Progress bar</div>
var width = 0;
function setProgress(){
var bar = document.getElementById('bar');
width+= 20;
bar.style.width = width + 'px';
console.log(bar.style.width);
if(width==200){
width=0;
}
}
window.onload = function(){
setInterval(setProgress, 1000);
}

CSS max() function alternative

I would like to set the min-height of a HTML element to the maximum of two values, but unfortunately css doesn't support max().
Here's my css code:
#content{ min-height:calc( 100% - 100px); }
The other value is constant number (400px). I think I have to use JS, but I cant figure out how to do that.
Here is my JS code:
function layout(){
var y = document.getElementById("content");
y.style.minHeight = Math.max(parseInt(y.style.minHeight), 400).toString + "px";
}
window.onload = layout;
window.onresize = layout;
alert(parseInt(y.style.minHeight)) gives me naN.
What am I doing wrong?
Regards
I can't determine a direct way to get the calculated result of the min-height style.
But the following function assigns it to the height of the element, from which we can get it as the element's new offsetHeight.
The function then restores the original height of the element:
function layout() {
var y = document.getElementById('content'),
h = y.offsetHeight;
y.style.height = getComputedStyle(y).getPropertyValue('min-height');
y.style.minHeight = Math.max(y.offsetHeight, 400) + 'px';
y.style.height = h + 'px';
} //layout
Working Fiddle

Square div with width based on percentage height

I'm trying to do the inverse of this fiddle, make a square with a width based on an a 100% based height.
http://jsfiddle.net/j372H/6/
<html style="height:100%">
<body style="height:100%">
<div id="square" style="background-color:black"></div>
</body>
</html>
$(window).ready(updateWidth);
$(window).resize(updateWidth);
function updateWidth()
{
var square = $('#square');
var size = square.width();
square.css('height',size);
}
Thank a lot for your help.
Seb.
In CSS set the height of the div also
<style>
html,body,#square { height:100%; }
</style>
then the reverse for your js function
function updateWidth()
{
var square = $('#square');
var size = square.height();
square.css('width',size);
}
Demo courtesy of wared - jsfiddle.net/wared/spSLP - - nice one, wared
$(window).ready(updateHeight);
$(window).resize(updateHeight);
function updateHeight()
{
var square = $('#square');
var size = square.height();
square.css('width',size);
}
NOTE - This needs the square div to have a height in the first place - height does not behave the same as width - just a heads up!
Using a simple math equation in the variable you can set a square div that re-sizes automatically.
change the 100 after * to give you a % width for your div.
see working jsfiddle for responsive width
$(document).ready(function() {
var height = ( $(window).height() / 100) * 100 ;
$('#square').width(height);
$('#square').height(height);
});
$(window).resize(function(){
var height = ( $(window).height() / 100) * 100 ;
$('#square').width(height);
$('#square').height(height);
});

Automatically adjusting font size to fit container

I have a defined style for div with fixed width and the text inside the div could have different lengths, like in this example. Is there any method using CSS and/or JS to adjust the text size in such a way that it will stay in bounds of the container?
this may work for you, try this
var originalFontSize = 12;
var divWidth = $('.cell').width();
$('.cell span').each(function(){
var spanWidth = $(this).width();
var newFontSize = (divWidth/spanWidth) * originalFontSize;
$(this).css({"font-size" : newFontSize, "line-height" : newFontSize/1.2 + "px"});
});​

Real image width with JavaScript

I have the next function:
function setImagesWidth(id,width) {
var images = document.getElementById(id).getElementsByTagName("img");
for(var i = 0; i < images.length;i++) {
// If the real width is bigger than width parameter
images[i].style.width=width;
//}
}
}
I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework.
images[i].offsetWidth returns 111 for an image of 109px width. Is this because 1px each side border?
Here is, hopefully, enough sample code to give you what you want:
var myImage = document.getElementById("myImagesId");
var imageWidth = myImage.offsetWidth;
var imageHeight = myImage.offsetHeight;
That should give you the numbers you need to derive the solution you want. I think you can write the rest of the code yourself. :)
EDIT: Here, I couldn't help myself - is this what you are after?
function setImagesWidth(id,width) {
var images = document.getElementById(id).getElementsByTagName("img");
for(var i = 0; i < images.length;i++) {
if(images[i].offsetWidth > width) {
images[i].style.width= (width + "px");
}
}
}
#Sergio del Amo: Indeed, if you check out my link you'll see that you want clientWidth instead.
#Sergio del Amo: You cannot, unfortunately, accept your own answer. But you do have an extraneous period in the "px" suffix, so let's go with this, including the clientWidth change:
// width in pixels
function setImagesWidth(id, width)
{
var images = document.getElementById(id).getElementsByTagName("img");
var newWidth = width + "px";
for (var i = 0; i < images.length; ++i)
{
if (images[i].clientWidth > width)
{
images[i].style.width = newWidth;
}
}
}
Careful, it looks like you might rather want clientWidth:
http://developer.mozilla.org/en/Determining_the_dimensions_of_elements
EDIT: Can i accept somehow this answer as the final one?
Since offsetWidth does not return any unit, the .px ending must be concatenated for the css attribute.
// width in pixels
function setImagesWidth(id,width) {
var images = document.getElementById(id).getElementsByTagName("img");
for(var i = 0; i < images.length;i++) {
if(images[i].offsetWidth > width) {
images[i].style.width= (width+".px");
}
}
}
Just in case you, the reader, came here from google looking for a way to tell what is actual image file pixel width and height, this is how:
var img = new Image("path...");
var width = image.naturalWidth;
var height = image.naturalHeight;
This becomes quite usefull when dealing with all kinds of drawing on scaled images.
var img = document.getElementById("img");
var width = img.naturalWidth;
var height = img.naturalHeight;
document.getElementById("info").innerHTML = "HTML Dimensions: "+img.width+" x "+img.height +
"\nReal pixel dimensions:"+
width+" x "+height;
<img id="img" src="http://upload.wikimedia.org/wikipedia/commons/0/03/Circle-withsegments.svg" width="100">
<pre id="info">
</pre>

Categories

Resources