Setting the margin of an img in Javascript - javascript

The code below adjusts the margin of an img, so it's centered in an div with width of 600px. It works in general, but sometimes it doesn't and a second call is required.
Edit: Forgot to mention: This function is triggered by another, who is setting the source of the image to another, therefore changing the image.
Any help?
function adjustMargin(imageId) {
var image = document.getElementById(imageId);
image.setAttribute("style", "margin: 0 " + (300 - image.clientWidth / 2).toString() + "px");
}
The not-so-well working example can be seen here.

use css:
#imgId {
margin: 0 auto;
display: block;
// you are subtracting 300px and dividing by 2
// so assume your image is 300px wide
width: 300px;
}
The img tag is an inline element and as margin: 0 auto will only work on block elements you have to include display: block on the img css.
An alternative to center inline elements is:
#imgId {
text-align: center;
}
Demo of both methods here

First - correct way for setting styles is:
image.style.margin = "margin: 0 " + (300 - image.clientWidth / 2).toString() + "px";
(well, maybe there is no difference, but .style propery is supposed to be used for changing style of elements with JS)
Second - are you sure image is already loaded when that code is executed? If no - image.clientWidth might be not available yet. You may need to use onload event to run that code when image is loaded for sure.
Third - as stated in Bruno's answer, margin:0 auto; will automatically place your image centered inside a div, so no JS required at all.
EDIT:
But with 3rd approach you have a problem because image is not a block element. In order to make it work do something like this:
<div style="
width: 600px;
"><img src="Bilder/re-tabouret/lukas_baumgartner_re_tabouret_1#b.jpg" alt="mainArticleImg" class="projektMainImg" id="01:00" style=""></div>
wrap image into div with specified width and update css like this:
img.projektMainImg {
margin: 0 auto;
max-width: 600px;
max-height: 400px;
display: block;
}
(see display:block added)
Or simply wrap image with a div with specified width and add text-align:center to its style (no display block and margins needed):
<div style="
width: 600px;
text-align: center;
"><img src="Bilder/re-tabouret/lukas_baumgartner_re_tabouret_1#b.jpg" alt="mainArticleImg" class="projektMainImg" id="01:00" style=""></div>
Wraper div is required in order to center image in left 600px area. Otherwise it will be centered relatively to <div class="projektImages">

Related

Slide up a "fixed height div" that splits a web page horizontally?

I need a box that slides up from the bottom of my page. I will use the box to show important information to new users. So for example, immediately after signup, the box will slide up with a welcome message.
I've made this jsfiddle that to some extend exemplifies the desired behaviour. It's just a div that gets slided up from the bottom:
$('.foot').addClass('slide-up', 500, 'easeOutBounce');
However, the code is only to exemplify, because the implementation is insufficient for the following reasons:
The bottom box has a pre-determined 500px height, because it's initially hidden 500px below the browser. Instead, I need just the box height to fit its content. The content will vary, and will even be changed through javascript once loaded.
The bottom box emerges on top of other elements. Instead, I want to split the screen in 2. A bottom half that has as much height as the box content needs. And a top half that behaves just like a regular web page, i.e. if there is too much content the user can just scroll down. To exemplify the described effect you can check this jsfiddle (the code has no relevance though)
How could achieve the described behaviour?
After experimenting with several methods, I ended up with a solution that combines some ideas given in freedomm-n's comments (modify the size of the main div) and in Nikhil's answer (use a flex container). You can see the result in this jsfiddle.
For the following markup:
<div id="divContainer">
<div id="divTop">
Main content
</div>
<div id="divFooter">
Footer content
</div>
</div>
And these styles:
html, body, form
{
margin: 0;
padding: 0;
overflow: hidden;
height: 100%;
}
#divContainer
{
width: 100%;
height: 100%;
}
#divTop
{
overflow-y: auto;
padding: 8px;
height: calc(100vh - 16px); /* Accounts for padding and border (if any) */
}
#divFooter
{
padding: 12px;
text-align: center;
border: 1px solid black;
border-top-left-radius: 25px;
border-top-right-radius: 25px;
}
.containerEnd
{
display: flex;
flex-direction: column;
}
.topEnd
{
height: auto;
flex-grow: 1;
}
This Javascript code is used to animate the div elements:
function slideUpFooter() {
var currentHeight = $('#divTop').height();
var footerHeight = $('#divFooter').outerHeight(true);
$('#divTop').animate(
{ height: currentHeight - footerHeight },
2000,
'easeOutBounce',
function () {
$('#divContainer').addClass('containerEnd');
$('#divTop').addClass('topEnd');
});
};
The function called at the end of the animation sets the flexbox parameters, to ensure that the footer sticks to the bottom of the page.
I have updated your Fiddle. Look below for details.
You don't need to use position: fixed for the .foot section, you could use position: relative instead. Since I noticed you were using flex, I took the liberty to fix this using the same.
Changes made
Firstly I suggest adding a div container, giving a class name say - container.
Make the container display: flex & change the default direction to flex-direction: column.
Now since you want the main-content to be scroll-able depending on its contents, you need to first set a height to this section with height: 200px; and then make it scroll-able using overflow-y: auto;
Let me know if you have any doubts.

HTML - CSS - How to left-align images in a centered and resizable parent

I have a lot of thumbnails in my page: I want them to be centered, but the last line looks awful while resizing and I have something like one or two orphan images floating in the center of the page.
The last line should be left-aligned.
How to do it?
I tried to insert another div with "margin:0 auto 0 auto;" but it doesn't work.
https://jsfiddle.net/4hw4fkm9/
What I try to have:
<div style="text-align:center;">
<img />
<img />
<img />
<img />
etc..
</div>
You should use CSS for this, not the HTML attribute "align", which is pretty old school. You can either float the images left, in which case they will stack to the left, or you could set all the images to display: inline-block, then use text-align: center on their container element (the div in this case).
Here are some references:
http://www.w3schools.com/css/css_float.asp
http://www.w3schools.com/cssref/pr_class_display.asp
I'm not sure if this is what you're looking for - as you mention that you both 'want them centered' but want them left-aligned, too.
What you can do is create another div that will act as a container, set width: 100% on the main div, set the width slightly lower on the container div and set margin: 0 auto; on the container. Then make the images relatively positioned with left:0;.
See Updated Fiddle Here. Is this what you're after?
EDIT: Re-Updated Fiddle for my attached comment. You can use set pixel values on the main and container div to account for the set pixel width of the thumbnails + any spacing that occurs.
Using the selectors in the fiddle.
.center {
text-align:center;
background-color:red;
margin:0 auto;
padding:0 20px;
}
.center:after{
content:'';
display:table;
clear:both;
}
img {
width: 100px;
height: 100px;
float:left;
}
From there the .center element would need a width of some multiple of 100px to include a fixed number of imgs. I added padding to make it look closer to the picture you provided.

Make <p> tag remaining width of div with a link (which has an icon as a background) to the right of it

This is my html:
<div id="cobcContainer" class='floatLeft' style="width: 50%">
<p id="containerText">Random long text here. This text takes up two lines when it is inside it's container div (inside cobcContainer).</p>
<a class="square bookIcon" href="/"></a>
</div>
In the CSS (there is a style.css which I do not have access to) the
<a class="square bookIcon" href="/"></a>
has a background image and the width of it is 100px.
There is not any other CSS in this. When I view the webpage, the container is 50% and the text appears first and then the link / icon appears below it. How do I make the link / icon appear to the right of the text (make the text aligned to the left of the icon / link)? I need this to be a responsive design so I am trying to use percentages here (other than the link / icon which has a fixed width of 100px).
JQuery / JS can be used.
Note: I am not allowed to use
<table>
tags nor
display: table-cell
(these rules were set by the corporation).
p is a block level element, so any element after it will be below it. and as you have defined 100px width for a tag,
1) you can do this,
#containerText{
display:inline-block;
}
and define some width to it.
2) Or simply put
.square { float:left; }
This will float to the left and a tag will just come beside it.
Are you looking for something like this? http://jsfiddle.net/swm53ran/63/
You can use
#containerText {
display:inline-block;
}
And in tandem (not necessary) to push the link to the right side of the div:
.bookIcon {
float:right;
}
If float:right isnt used, then the link will be on the right, right next to the text
You can set the width of p tag using calc and add a float: left to the anchor tag.
a.square {
width: 100px;
display: block;
height: 10px;
float: left;
}
p {
float: left;
width: calc(100% - 100px);
margin: 0;
}
Fiddle

Overflow:scroll doesn't work when I add content to div

I have a div on my page with the following styles and no content to begin with:
#chatwindow {
width: 500px;
height: 50px;
overflow-y: scroll;
margin: 5px auto;
background: white;
border: 1px solid black;
}
Now, I have a simple Javascript function which adds new lines to the div:
function updateChat(response) {
$('#chatwindow').append('<p>' + response + '</p>');
$("#chatwindow").attr({ scrollTop: $("#chatwindow").attr("scrollHeight") });
}
It's supposed to add a line to the div and scroll to the top. However, after the content within the div becomes too large for the div, the overflow doesn't scroll - it remains invisible beyond the lower border of the div. What do I do (preferably with CSS alone) to make the div's scrollbar show up when the content becomes too large?
Fiddle
scrollTop is not an HTML attribute, it is however a jQuery method, among other things ?
$("#chatwindow").scrollTop( $("#chatwindow").attr("scrollHeight") );
note that scrollHeight is not an HTML attribute either, unless you added it for some reason, hard to tell without the markup, but you're probably looking for the native scrollHeight property
$("#chatwindow").scrollTop( $("#chatwindow").prop("scrollHeight") );

Overflow scroll on y axis with fixed height

I have an apparently easy problem which is:
<div class="container">
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
</div>​
I have 3 divs inside a container: A and B have fixed heights. C must have an extendable height, it extends along with the container height. If the content inside C are too big, I'd like C to scroll but to keep A and B in the same place.
Code in: http://jsfiddle.net/V2c9G/
I'm not able to do it.
I tried:
<div class="container">
<div class="a"></div>
<div class="b"></div>
<div class="xxx" style="overflow-y:scroll">
<div class="c"></div>
</div>
</div>​
without success. The container div it's supposed to resize along the browser.
A complex example would be http://www.sencha.com/examples/#overview (I'm talking about the layout, make the browser smaller and you will see scrolls apperaring hile the headers keeps fixed) but it's not a solution since it uses JS to recalculate the heights.
Any idea?
Edit 3:
This is my recommended solution, which uses CSS from the Edit 2 below as a fallback, but uses JavaScript to resize your divs appropriately onload and when your window size changes. The CSS solution provides a decent starting point if the client has JavaScript disabled, and the JavaScript is such that it really shouldn't affect the performance of the page, so I see no reason not to use JavaScript to perfect what you want to see. A working fiddle can be seen here. Also, here is the appropriate JavaScript code:
var resizeDiv = function(){
document.getElementById('c').style.height = getWindowHeight() - 64 + 'px';
};
//Framework code
var getWindowHeight = function(){
if (window.innerHeight) {
return window.innerHeight;
}
if (document.body && document.body.offsetHeight) {
return document.body.offsetHeight;
}
if (document.compatMode=='CSS1Compat' &&
document.documentElement &&
document.documentElement.offsetHeight ) {
return document.documentElement.offsetHeight;
}
return 740;//provide a default height as a fallback
};
//resize on pageload
window.onresize = resizeDiv;
setTimeout(resizeDiv);
I think you need to adjust the absolute height on your third div to take up the rest of the space (either absolutely or with percentages), set overflow to hidden on the parent div, and let the content in the third inner div determine whether to show the scrollbar or not. Here's an updated fiddle using the absolute height method.
Edit:
From your "Imagine the container is the browser" comment (which to me means the scrollbar should be on the container), all you'd really have to do is set the overflow to 'scroll' and height in the third div to 'auto'. Here's an updated fiddle for that.
Edit #2:
According to your comment on this question, it sounds like you need to go with the percentage method. The most straightforward would be to make the height of a, b, and c a percentage (I had to tweak the margins to get it to fit for all zooms). Unfortunately with this method, the top components will not be fixed, and it sounds like you may be displaying static content there that would look funky. Thus, another option is to pick a minimum supported size for your browser window and adjust the percentage of the third element so that it just fits. Here's a fiddle for that. However, the downside there is that you'll have more empty space at the bottom of the page the bigger the height of the window, and you'll have 2 scrollbars below a certain height. To really do this properly with the fixed sized divs at the top, you'll need to add an event listener to the window.resize method and resize your third div when that happens appropriately based on the new size of the window.
Note: It is times like this where I wish the W3C would approve percentages plus pixels for their height, width, and other sizing properties!
I think you might be searching for something like this: http://jsfiddle.net/QsLFt/.
However, I'm not sure how to get rid of the divs hiding the scrollbar, the easiest solution would probably be to set it a fixed width?
You need to apply overflow-y:scroll in .container
See this,
http://jsfiddle.net/v4ZtN/
Edit (after comments):
Css:
.container{
background-color: red;
width: 90%;
margin: 0 auto;
height:220px;
}
.a{
background-color: yellow;
height: 30px;
margin: 2px;
}
.b{
background-color: blue;
height: 30px;
margin: 2px;
}
.c{
background-color: green;
overflow-y: scroll;
height:inherit;
}
Html:
<div class="container">
<div class="a"></div>
<div class="b"></div>
<div class="c"><img src="http://www.boingboing.net/images/_documents_anemone_images_anemone850-1.jpg" alt=""/></div>
</div>
Edit:2 (after comments)
Change .c style with this.
.c{
background-color: green;
overflow-y: scroll;
height:100%;
}
Check this fiddle:
http://jsfiddle.net/XM4gH/6/
div only show scroll when you put some data in it, here is the result;
jsfiddle
Based on what's currently up on your jsFiddle, I think you can simply add this to the style declarations for your .container class:
overflow:hidden;
You'll have to actually add content to the .c div to see any scrolling however.
did this anser is match to your request ? enter link description here
.container{
background-color: red;
width: 90%;
margin: 0 auto;
height: 315px;
}
.a{
background-color: yellow;
height: 30px;
margin: 2px;
width: 90%;
}
.b{
background-color: blue;
height: 30px;
margin: 2px;
width: 90%;
}
.c{
background-color: green;
height: 250px;
margin: 2px;
width: 90%;
overflow-y: scroll;
}
​
It's hard to tell exactly what you are trying to do based on the question, but if this is the desired result, these are the problems I discovered in your code:
You needed to hide overflow on the red box, so the green box does not extend beyond the container
In the green box, if there is enough data to extend, you want a scroll bar. This was working, but the height you had set specifically (250px) was enough to extend out of the container. You want a specific height here, the number is whatever is remaining in the container. I got 132px. Then with the overflow scroll applied, anything that extends beyond this height will be scrollable.

Categories