I have a TinyMCE that is set over a TextArea, and I want this editor area to ocuppy all the space of its parent div, all times.
I have a JS function that get the current space and set the textarea.style.height to it, but when I enables TinyMCE it seems to stop working.
Also, the textarea has width: 100%; it doesn't resize by HTML rendering when it's using TinyMCE too.
Any ideas?
Nowadays, you should use the autoresize plugin that comes with tinyMCE. You will have to call tinyMCE like this (jQuery version):
$('.tinymce').tinymce({
theme : 'advanced',
plugins : 'autoresize',
width: '100%',
height: 400,
autoresize_min_height: 400,
autoresize_max_height: 800,
});
I made the experience, that it may be helpful to manually call the resizing in the init_instance_callback to provide the correct height on init. Add this parameter to the passed options, if you need this:
init_instance_callback: function (inst) { inst.execCommand('mceAutoResize'); }
The point is that TinyMCE generates an iframe in the place of the textarea, with this ID: originalID+"_ifr", and a table originalID+"_tbl" for holding the controls and the editor area.
To make fluid width:
document.getElementById(id+'_tbl').style.width='100%'
To make fluid height:
Change dinamically document.getElementById(id+'_ifr').style.height to the height you want, through JS.
This is the script I'm using for this:
function toScreenHeight(id, minus) {
var height;
if (typeof(window.innerHeight) == "number") //non-IE
height = window.innerHeight;
else if (document.documentElement && document.documentElement.clientHeight) //IE 6+ strict mode
height = document.documentElement.clientHeight;
else if (document.body && document.body.clientHeight) //IE 4 compatible / IE quirks mode
height = document.body.clientHeight;
document.getElementById(id).style.height = (height - minus) + "px";
}
You can use the code and function calls inside onload and onresize body events.
in tinymce 3.4.6,
set
width:'100%'
in init option will solve the problem.
If you're doing tiny MCE dynamically via JS, you can run into timing issues where the MCE editor is not yet available for style adjustments. To combat this, you can use an old school timeout.
In this example, I'm using a "j" namespace for JQuery. If your editor is in a fluid div that changes size, you may want include this in a $(window).resize(function() { }); listener.
setTimeout(function(){
$j('.mceEditor').css('width','100%').css('minHeight','240px');
$j('.mceLayout').css('width','100%').css('minHeight','240px');
$j('.mceIframeContainer').css('width','100%').css('minHeight','240px');
$j('#'+[INSERT TEXTAREA ID HERE]+'_ifr').css('width','100%').css('minHeight','240px');
},500)
None of the above were working for me in TinyMCE v4, so my solution was to calculate the height based on the toolbars/menu bar/status bar, and then set the height of the editor, taking those heights into consideration.
function resizeEditor(myHeight) {
window.console.log('resizeEditor');
myEditor = getEditor();
if (myEditor) {
try {
if (!myHeight) {
var targetHeight = window.innerHeight; // Change this to the height of your wrapper element
var mce_bars_height = 0;
$('.mce-toolbar, .mce-statusbar, .mce-menubar').each(function(){
mce_bars_height += $(this).height();
});
window.console.log('mce bars height total: '+mce_bars_height);
myHeight = targetHeight - mce_bars_height - 8; // the extra 8 is for margin added between the toolbars
}
window.console.log('resizeEditor: ', myHeight);
myEditor.theme.resizeTo('100%', myHeight); // sets the dimensions of the editable area
}
catch (err) {
}
}
}
In my case, I wanted the editor window to match the width and height of the actual window, since the editor would come up in a popup. To detect changes and resize, I set this to a callback:
window.onresize = function() {
resizeEditor();
}
With version 4 and the option to use flexbox layout in the browser I did the following to get a full width,height editing experience of the parent div.
It should be easy to put the css into a file if you prefer adding it to your existing styles.
var css = '.tinycme-full .mce-edit-area {display:flex;flex-flow:column;} .tinycme-full .mce-edit-area iframe {flex:1 1 auto;} .tinycme-full {height:100%;} .tinycme-full .mce-tinymce.mce-container { width:100%;height:100%;border:0; } .tinycme-full .mce-panel{border:0} .tinycme-full .mce-container-body.mce-stack-layout {display: flex; flex-flow: column;height: 100%;} .tinycme-full .mce-stack-layout-item{ flex: 0 0 auto;} .tinycme-full .mce-edit-area{flex:1 1 auto;} ',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet["cssText"] = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
The idea is that it make all the needed divs take up as much column space as needed to fill the parent 100% and its done by putting a div around your textarea: <div class="tinycme-full"> <textarea ... /></div>
No jquery or other dependencies are needed andd it now fills the parent 100%.
I had the same problem, after reading this thread I ended up with this code
init_instance_callback: function (inst) {
setTimeout(function () {
document.getElementById(inst.id + '_ifr').style.height= (document.getElementById("theContainerDiv").offsetHeight-85) + 'px';
},1000);
},
I resize the "_ifm" element instead of the "_tbl", since resizing the "_tbl" didn't resize the edit area for me. Then I leave some space for the toolbar and statusbar by making the "_ifr" 85 pixels shorter then the container div.
I had to use setTimeout to make it work, maybe because I have an animation that displays the container element.
I'm using pure css solution to achieve this (tinyMCE 4.0.20).
Set iframe height to 100%:
tinymce.init({
height: '100%'
})
Add styles to auto-resize iframe container:
.mce-tinymce { height: auto; width: 100%; position: absolute; left: 0; top: 0; bottom: 0; }
.bq-editor .mce-container-body { height: 100%; }
.bq-editor .mce-edit-area { position: absolute; top: 57px; bottom: 0; width: 100%; height: auto; }
Note: I have one toolbar line, and top: 57px; in .bq-editor .mce-edit-area is toolbar padding.
SyCoDeR is right but I followed a slightly different path though probably with the same results.
/*Container, container body, iframe*/
.mce-tinymce, .mce-container-body, #code_ifr {
min-height: 100% !important;
}
/*Container body*/
.mce-container-body {
position: absolute;
bottom: 0;
left: 0;
right: 0;
}
/*Editing area*/
.mce-container-body .mce-edit-area {
position: absolute;
top: 69px;
bottom: 37px;
left: 0;
right: 0;
}
/*Footer*/
.mce-tinymce .mce-statusbar {
position: absolute;
bottom: 0;
left: 0;
right: 0;
}
Revised because TinyMCE changes the id's with menu/toolbar additions or deletions. This works no matter what you do with it.
This is an old question, but apparently it still drags a lot of attention nowadays (Second half of 2020).
Sadly, with the release of the TinyMCE v5, most of the workarounds I found simply do not work anymore. I am sure they worked once, but every TinyMCE release seems to bring new "constrainings" that cripple those workarounds...
Without making it a discussion, I believe it is the cost of evolution. For an old product like the TinyMCE, it is incredible to see it is still around and kicking, staying way above the competition. It is by far one of the most efficient and flexible solutions for all environments, including mobile and for those new languages and frameworks that born since (which seems to be a trend lately, with new ones coming out of the blue every day).
So, with that in my mind, and after so many (failed) attempts to make most of the proposed solutions work, I decided to dig into the source code (TinyMCE v5.4) to better understand it. What I found was a much superior product overall, and that the solution everyone has been looking for is much simpler to implement than I was anticipating.
With no further delay, here my solution that simply works. It implements an editor that takes the entire document area (or whatever area you want), which WILL resize with the browser, requiring NO script, NO hack, and NO trick that could cause cross-browsing issues. Here's how:
Give to your <html> and <body> DOM objects the missing properties of size and adjust the spacing accordingly to your needs:
html, body {
width : 100%;
height : 100%;
margin : 0 !important;
padding : 0 !important;
overflow : hidden; /* Required if you want to have the editor taking the entire page. */
/* Otherwise, set as you need it. */
}
TinyMCE suggests the <textarea> to be embedded inside a <form> object. Regardless if you use it as suggested or not, simply give to it and ID and the following CCS properties (in my case, it is set as <form method="post" id="editorBase">):
#editorBase {
display : block !important;
width : 100% !important;
height : 100% !important;
}
In the TinyMCE Init method, add or modify the following settings:
tinymce.init({
// Required Settings:
width : '100%', // Note value is set as "string".
height : '100%', // Note value is set as "string".
resize : false, // Suggestion: disable the statusbar resizing. :)
// Suggested Settings:
toolbar_sticky : true, // Keep the menu and tollbar in a fixed position .
toolbar_location : 'top', // You can try 'top', 'bottom' or 'auto'.
toolbar_mode : 'floating', // It is simply a button behavior settings.
// Options are: 'floating', 'sliding', 'scrolling', or 'wrap'.
});
Yet in the TinyMCE Init settings, find the plugins item and remove the autoresize option from it (it is the most important step of all!).
Done! Try and test it! (YES! It is all done!)
With those simple adjustments you can set the editor to fit any design. Feel free to adjust it as needed. Just don't forget to set the width and the height properties in the TinyMCE Init settings as strings, and keep it consistent with the CSS settings for the <form>.
The reason to use strings in the width and height properties of the TinyMCE Init settings instead of numeric values is to allow you to use "%", "em", "pt", etc... Otherwise, the presented solution would never work.
Another trick to make it even more neat is to set the editor as borderless skin (a feature only present in the "professional" version of TinyMCE). No, it is not a hack, it is a siple adjustment to the CSS and totaly allowed by TinyMCE's EULA and Licensing. Simply add the following CSS to your page Stylesheet and it enjoy a borderless editor for free:
.tox-tinymce { border:none !important; }
Could not be easier than that.
Happy coding!
The wrapper of iframe (its ID finish by _ifr) is the first parent of span that it has application as role .
Thus, To get the wrapper :
$('span[role=application]').parents(':eq(0)')
So to Resize height:
$('[id$=_ifr]').css('height',$('span[role=application]').parents(':eq(0)').css('height'))
To resize width
$('[id$=_ifr]').css('width',$('span[role=application]').parents(':eq(0)').css('width'))
None of these solutions worked 100% for me. I needed the height to adjust on initialization and during edits. What I did is grab the height of the HTML element in the iFrame, and then applied the height to the iFrame with an extra 100px.
Here's my solution: (added img max-width for responsive images)
on initialization
setup: function(editor) {
editor.on('init', function (e) {
$("#editor_textarea_ifr").contents().find('img').css("max-width","100%");
iframeHeight = $("#editor_textarea_ifr").contents().find("html").height();
$("#editor_textarea_ifr").css("height",iframeHeight + 100);
});
},
on node change (edits)
init_instance_callback: function (editor) {
editor.on('NodeChange', function (e) {
$("#editor_textarea_ifr").contents().find('img').css("max-width","100%");
iframeHeight = $("#editor_textarea_ifr").contents().find("html").height();
$("#editor_textarea_ifr").css("height",iframeHeight + 100);
});
}
Related
I'm working with Bootstrap and I want to put some photos into my div and I want them to be all at the same size ("standardize").
If they're too big (and they will always be) I want to resize them to fit in my div and crop them if necessary.
For the moment her is what I do :
I've tried to change the style of the image in jQuery in a function:
• If the height is bigger than the width, I switch the style to max-width:100% and height auto.
• Inversement if the width is bigger than the height.
But I'm still new to jQuery and I am probably doing something wrong; can someone light my lantern please?
Here is my jQuery
$(document).ready(function(){
photoResize();
$(window).resize(function(){
photoResize();
});
});
function photoResize(){
image_w = $('img').width();
image_h = $('img').height();
if(image_h > image_w)
{
$('img').css("max-width","100%");
$('img').height("auto");
}
else if(image_w > image_h)
{
$('img').css("max-height","100%");
$('img').width("auto");
}
}
And here is a Fiddle for a better view : https://jsfiddle.net/Baldrani/DTcHh/9801/
Simplicity
I do this quite often in the CMS we use at work for galleries etc. The method I use involves a jQuery library called imgLiquid.js.
This will turn an inline image into a background image on the parent div. It's good because you can achieve your desired effect. It will crop the image (as it technically becomes a background image) and will apply background-size: cover; and background-position: center center; as inline styles.
You can find the plugin here
To initialize the plugin you just need:
$(".myele").imgLiquid();
Overheads
The plugin is very small (roughly around 5.106 KB) so you don't need to worry about adding weight to the page. It really it the most simple method I've come across (bar using thumbnails generated from the sever-side - see note at the bottom).
Cue CSS
I've tested this thoroughly and found it gives excellent results. You may then ask... what happens to my parent divs (as technically the plugin hides the img element - which therefore means the parent element doesn't know what height to make itself).
An easy method to make things work responsively, or not:
.myelement:before{
content: "";
padding-top: 50%;
display: block;
}
This CSS will give your heights back to the wrapping element. So if you wanted certain proportions you could use this math:
h / w * 100 = your percentage for the padding-top.
Working Example
Small note
Technically if I had the control I'd advise just using thumbnails.. I assume you're using some sort of system that could technically just render cut down versions of the images? The reason I use this method — and suggested it — is that I don't have control over the CMS and I'm assuming you just want to manage the code that's being produced as it's not stated.
if you want to make your images the same size then you dont need any javascript or calculations, why not just set it in css?
.someUniqueContainer img{
width:300px;
height:300px; // or what ever height you want
}
I'm guessing that in reality you actually want to crop all your images to a set width/height. if that's the case you'll need a serverside script for that.
where are the images coming from? it would be easyer to just edit them. if they are coming from a user then you would resize/crop on the server on file upload
There were several mistakes in your code.
Please look at this jsfiddle, please see https://jsfiddle.net/DTcHh/9796/
$(document).ready(function () {
photoResize();
$(window).resize(function () {
photoResize();
});
});
function photoResize() {
image_w = $('img').width();
image_h = $('img').height();
if (image_h > image_w) {
$('img').css("max-width", "100%");
$('img').height("auto");
} else if (image_w > image_h) {
$('img').css("max-height", "100%");
$('img').width("auto");
}
}
sth like this?, although this is pure css, not jquery included, might not be suit in your case..
body {
margin-top:20px
}
.col-xs-3 {
margin: 5px 0;
width: 500px;
height:120px
}
.col-xs-3 > div {
width: 100%;
height: 120px;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
JsFiddle
I have this code:
$(document).ready(function(){
/* SET VAR FOR IS OPEN */
var isopen = 0;
/* SHOW FIRST NEWS ON STARTUP EXTENDED */
/* SET ALL .TRIGGER PARENT .CONTAINER TO FIXED HEIGHT WITH CUTTED CONTENT (OVERFLOW) */
$('.trigger:not(:first)').css({
height: "70",
overflow: "hidden"
}, 200 );
/* CLOSE THE CLICKED ELEMENT */
$('.trigger').click(function() {
if (isopen == 0) {
// SET ALL TRIGGER TO 70PX HEIGHT
$('.trigger').css({overflow: "hidden"}).animate({
height: "70",
}, 200 );
$(this).animate({
height: "350",
}, 200 );
} else {
alert('this Alert shuld show up if isopen=1');
}
});
})
Its a news content of a website.
The user see three divs.
2 are cutted to 70px Height
The first news is extended to its original height.
after click the height: auto; does not work. So the height is set to 350px. How to get a dynamic height? Thanks!
Difficult to 100% verify my answer as I would need a fiddle/plunker with your HMTL/CSS/JS to work with, but here is my suggestion that I think will help.
Rather than explicitly setting CSS styles to the elements via JavaScript, via methods like 'css(value, property)', instead add or remove classes to the elements via 'addClass()', 'removeClass()', or 'toggleClass()'.
New look JS:
$('.trigger').click(function() {
$(this).toggleClass('is-closed');
}
New look CSS:
.trigger {
// Your current UI component styling, but no height specified
}
.trigger.is-closed {
height: 70px;
overflow: hidden;
}
The difference here being, is that you're not trying to assert "height: auto" as an overriding style for "height: something else", you are simply adding and withdrawing the fixed height on open/close - which I would suggest is much less error prone much more likely to bring about the behaviour that you want.
Furthermore, this is also a good practice to follow in any event because of the following reasons:
Separation of concerns, your styling belongs in your CSS files rather than JavaScript (i.e. component styles all together)
Reusable code, these styles reflecting the "closed" state could be re-used across all instances of this UI component, as well as others components, rather than re-written every time in JS click handler functions
Modifying CSS via jQuery functions such as 'css(property, value)' is a bad idea, it results in the styles added as inline styles in the DOM (e.g. style="height: 70px;") and this will take priority over other CSS, making managing your CSS harder and debugging presentation errors more difficult
This approach also has the added benefit of reducing the length and clarifying your JavaScript code significantly.
Height Animation
The above code will not provide the height animation that you currently have.
The solution here is to adopt a CSS transition approach rather than animating via JavaScript. Article: http://www.w3schools.com/css/css3_transitions.asp
This will again mean that all of your component related styling will remain together in one place, but CSS animation also performs much better/renders faster than JavaScript animation does.
Hope this helps.
Setting css height in javascript is basically adding an element style tag to it, which will override the css file always due to the rendering rules of css. If you set the value to an explicit height, to get it back to height: auto, you either have to write height: auto to it in the javascript or remove the style element you added completely.
This is currently happening in chrome, in firefox I haven't had this issue (yet).
Here is a VERY simplified version of my problem.
HTML:
<div class="thumbnail">
Click me!
</div>
CSS:
div {
width: 200px;
height: 300px;
background-color: purple;
}
a {
position: absolute;
}
#media (max-width: 991px) {
div {
height: 200px;
}
}
Javascript:
$(document).ready(function () {
var $parent = $('#clickMe').parent();
function resize() {
$('#clickMe').offset({
top: $parent.offset().top + $parent.height()-$('#clickMe').height()
});
}
$(window).on('resize', resize);
resize();
});
The problem:
So what does this give when I resize (without dragging)? Well javascript launches first and sets the position of the <a></a> , then CSS applies the height change if we are < 992 px.
Logically the button is now visually at the outside of the div and not on the border like I had originally defined it to be.
Temporary solution proposed in this post.
jQuery - how to wait for the 'end' of 'resize' event and only then perform an action?
var doit;
$(window).on('resize', function(){ clearTimeout(doit); doit = setTimeout(resize, 500); });
Temporary solution is not what I'm looking for:
However, in my situation I don't really need to only call 'resize' when the resizing event is actually done. I just want my javascript to run after the css is finished loading/ or finished with it's changes. And it just feels super slow using that function to 'randomely' run the JS when the css might be finished.
The question:
Is there a solution to this? Anyone know of a technique in js to wait till css is completely done applying the modifications during a resize?
Additional Information:
Testing this in jsfiddle will most likely not give you the same outcome as I. My css file has many lines, and I'am using Twitter Bootstrap. These two take up a lot of ressources, slowing down the css application (I think, tell me if I'm wrong).
Miljan Puzović - proposed a solution by loading css files via js, and then apply js changes when the js event on css ends.
I think that these simple three steps will achieve the intended behavior (please read it carefully: I also suggest to read more about the mentioned attributes to deeply understand how it works):
Responsive and fluid layout issues should always be primarily (if not scrictly) resolved with CSS.
So, remove all of your JavaScript code.
You have positioned the inner a#clickMe element absolutely.
This means that it will be positioned within its closest relatively positioned element. By the style provided, it will be positioned within the body element, since there is no position: relative; in any other element (the default position value is static). By the script provided, it seems that it should be positioned within its direct parent container. To do so, add position: relative; to the div.thumbnail element.
By the script you provided, it seems that you need to place the a#clickMe at the bottom of div.thumbnail.
Now that we are sure that the styles added to a#clickMe is relative to div.thumbnail, just add bottom: 0px; to the a#clickMe element and it will be positioned accordingly, independently of the height that its parent has. Note that this will automatically rearrange when the window is resized (with no script needed).
The final code will be like this (see fiddle here):
JS:
/* No script needed. */
CSS:
div {
width: 200px;
height: 300px;
background-color: purple;
position: relative; //added
}
a {
position: absolute;
bottom: 0px; //added
}
#media (max-width: 991px) {
div {
height: 200px;
}
}
If you still insist on media query change detection, see these links:
http://css-tricks.com/media-query-change-detection-in-javascript-through-css-animations/
http://css-tricks.com/enquire-js-media-query-callbacks-in-javascript/
http://tylergaw.com/articles/reacting-to-media-queries-in-javascript
http://davidwalsh.name/device-state-detection-css-media-queries-javascript
Twitter Bootstrap - how to detect when media queries starts
Bootstrap: Responsitive design - execute JS when window is resized from 980px to 979px
I like your temporary solution (I did that for a similar problem before, I don't think half a second is too long for a user to wait but perhaps it is for your needs...).
Here's an alternative that you most likely have thought of but I don't see it mentioned so here it is. Why not do it all through javascript and remove your #media (max-width.... from your css?
function resize() {
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
if(width<992){
$("div").each(function(e,obj){$(obj).height(200);});
}
$('#clickMe').offset({
top: $parent.offset().top + $parent.height()-$('#clickMe').height()
});
}
In the html page, put the link to css file in head section; next, put the link to js file just before the /body tag and see what happens. In this way css will load always before js.
Hope this help you.
Did you try to bind the resize handler not to the window but to the object you want to listen to the resize ?
Instead of
$(window).on('resize', resize);
You can try
$("#clickMe").on('resize', resize);
Or maybe
$("#clickMe").parent().on('resize', resize);
var didResize = false;
$(window).resize(function() {
didResize = true;
});
setInterval(function() {
if (didResize) {
didResize = false;
console.log('resize');
}
}, 250);
I agree with falsarella on that you should try to use only CSS to do what you are trying to do.
Anyway, if you want to do something with JS after the CSS is applied, I think you can use requestAnimationFrame, but I couldn't test it myself because I wasn't able to reproduce the behavior you explain.
From the MDN doc:
The window.requestAnimationFrame() method tells the browser that you
wish to perform an animation and requests that the browser call a
specified function to update an animation before the next repaint. The
method takes as an argument a callback to be invoked before the
repaint.
I would try something like this:
var $parent = $('#clickMe').parent();
function resize(){
$('#clickMe').offset({
top: $parent.offset().top + $parent.height()-$('#clickMe').height()
});
}
window.onresize = function(e){
window.requestAnimationFrame(resize);
}
window.requestAnimationFrame(resize);
Anyone know of a technique to wait till css is completely done loading?
what about $(window).load(function() { /* ... */ } ?
(it executes the function only when the page is fully loaded, so after css loaded)
I'm developing a mobile version of a TYPO3 site. There I use the plugin nivoslider which uses the official known Nivo Slider. Now I have to reduce the size of the slider. How can I reach this?
In TYPO3 there is a setting on the plugin page with width and height but this would affect also the full size website. Because there is no manual I don't think I can use Typoscript to set the width and the height afterwards.
I tried to set the width with CSS
.nivoSlider {
width: 300px !important;
height: auto !important;
}
.nivoSlider img {
width: 300px !important;
height: auto !important;
}
but when the slider is loaded it uses the normal size of the pictures. Only the slider container itself is cropping the images but it has a wrong height (only dots and a small part of the image can be seen).
I also tried to look into the documentation to see if I could set the width and the height somehow. But I didn't found any settings. Are there any javascript/jquery solutions I could use? This doesn't work:
$(document).ready(function() {
$('.nivoslider img').each(function(index, element){
alert('test');
$(this).width(300);
var src = $(this).attr("src");
src = 'fileadmin/templates/timthumb/timthumb.php?src=' + src + '&w=300';
$(this).attr("src", src);
});
});
It seems that .nivoslider is built afterwards, but my code is executed before. This is the confirmation:
if ($('.nivoslider').length != 0) {
alert('element found');
}else{
alert('element NOT found');
}
The code above gives me element NOT found, because the initialisation of extension is at the end of the header and my code is before. How can I include Javascript code at the end of the header in TYPO3?
Now I think I will use this CSS, because I don't see any solution:
.nivoslider {
display: none;
}
You want to take a look at this...
http://nivo.dev7studios.com/2012/05/30/the-nivo-slider-is-responsive/
########################## UPDATE #############################
The above link has been removed, please see the following for example:
http://www.flynsarmy.com/wp-content/uploads/2012/09/nivoslider/index.html
change height by changing the height in the img tag in the html file and change width by changing the width in .slider-wrapper in style.css.
I have my div (#box) centering in the middle of the browser window which is groovy for browsers that are 600px vertical or taller. If the window is smaller than that, content at the top of the div gets sheared off, and the scroll bar only scrolls the page up (when I pull the scroll bar down), so it's impossible to see anything hidden above the top edge of the window even when the scroll bar is at its top-most position.
Here's how I center my div--you can see why the top of the div gets cut off in smaller browser windows.
{position: absolute; top: 50%; left: 50%; width: 1930px; height: 607px; margin-left: -965px; margin-top: -302px;}
(It's really wide to accommodate the animation working on even the widest screens--the width isn't an issue.)
Here's a page to look at: http://ianmartinphotography.com/test-site/
And my CSS: http://ianmartinphotography.com/test-site/css/basic.css
This is easily fixed in my CSS style sheet, but it seems like I can't have it both ways for monitors greater than 600px and monitors smaller than 600px.
So, how do I detect a browser window size and then select one of two different CSS style sheets? One for small windows, another for larger windows? Is there a jquery script that will do this for me?
Or, is there another way to make my div center in the middle of the browser window with CSS that will allow scrolling so that the top of the div can be accessed on smaller browser windows?
Thanks for your thoughts!
#media queries are my preference (saw that you don't like them as a solution per se), but they really could do the trick - especially if you adjust your css a little to accommodate.
<link...media="only screen and (max-height: 600px)" href="small-device.css" />
small-device.css = div.container { ... height:500px; margin:50%; ...}
<link...media="only screen and (min-height: 601px)" href="big-device.css" />
big-device.css = div.container {... height:600px; margin:50%; ...}
You may also have a little more luck by removing your absolute positioning and taking advantage of normal document flow. It would help you to add things like { overflow-y:scroll; }
to those hidden-by-screen-height divs.
I think in the end, if you're trying to design around hand-held devices, you'll need media queries to some extent. My Android screen (for example) has 3 display options (low, medium, hi def). All 3 crop pages differently.
You can determine window size by Jquery
$(window).width();
$(window).height();
or
$(document).width();
$(document).height();
then change css
$("link").attr("href", "blue.css");
Something like this:
$(document).ready(function(){
if($(document).height() > 600 or $(window).height() > 600){
$("link").attr("href", "600+.css");
} else {
$("link").attr("href", "600-.css");
}
});
A solution that works in all major browsers. No JS needed. Vertically/horizontally centered, scrollable, sticks to the top when content is larger than viewport.
HTML:
<div id="body">[your content goes here]</div>
CSS:
html, body {
width: 100%;
height: 100%;
}
html {
display: table;
}
body {
display: table-cell;
vertical-align: middle;
}
#body {
margin: 0 auto;
}
Don't forget to apply the last rule, it will actually perform the horizontal centering.
Just did a bit of googling and found this:
http://www.ilovecolors.com.ar/detect-screen-size-css-style/
does that work for you?
Try the Less CSS Framework: http://lessframework.com/,
You do not need JavaScript, but rather you can use CSS #Media to set styles based on resolution/ screen size.
Best of luck
Use the following JavaScript conditional to detect screen size.
function x() will handle inserting the CSS link in the <head> tag. All you need to do is call the function and pass in the CSS file name.
< script type = "text/javascript" >
<!--
function x(y) {
var styles = y;
var newSS = document.createElement('link');
newSS.rel = 'stylesheet';
newSS.href = 'data:text/css,' + styles;
document.getElementsByTagName("head")[0].appendChild(newSS);
}
if ((screen.width >= 1024) && (screen.height >= 768)) {
x('file.css');
}
else {
x('file1.css');
}
//-->
< /SCRIPT>
If "document_height" not work, try "window_height" i comment it in code!
$("link").attr("href", "css_file_path"); // here must insert path to your css, replace it in the code below
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
document_height = $(document).height();
//window_height = $(window).height();
//if(window_height > 600){
if(document_height > 600){
alert('Bigger than 600px height: ' + $(document).height());
$("link").attr("href", "600+.css"); // Here load css if window is bigger then 600px;
} else {
alert('Smaller than 600px height: ' + $(document).height());
$("link").attr("href", "600-.css"); // Here load css if window is smaller then 600px;
}
});
</script>