I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.
I am wrapping everything in this div:
#scroll {
height:400px;
overflow:scroll;
}
Is there a way to keep it scrolled to the bottom by default using JS?
Is there a way to keep it scrolled to the bottom after an ajax request?
Here's what I use on my site:
var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;
This is much easier if you're using jQuery scrollTop:
$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
Try the code below:
const scrollToBottom = (id) => {
const element = document.getElementById(id);
element.scrollTop = element.scrollHeight;
}
You can also use Jquery to make the scroll smooth:
const scrollSmoothlyToBottom = (id) => {
const element = $(`#${id}`);
element.animate({
scrollTop: element.prop("scrollHeight")
}, 500);
}
Here is the demo
Here's how it works:
Ref: scrollTop, scrollHeight, clientHeight
using jQuery animate:
$('#DebugContainer').stop().animate({
scrollTop: $('#DebugContainer')[0].scrollHeight
}, 800);
Newer method that works on all current browsers:
this.scrollIntoView(false);
var mydiv = $("#scroll");
mydiv.scrollTop(mydiv.prop("scrollHeight"));
Works from jQuery 1.6
https://api.jquery.com/scrollTop/
http://api.jquery.com/prop/
alternative solution
function scrollToBottom(element) {
element.scroll({ top: element.scrollHeight, behavior: 'smooth' });
}
smooth scroll with Javascript:
document.getElementById('messages').scrollIntoView({ behavior: 'smooth', block: 'end' });
If you don't want to rely on scrollHeight, the following code helps:
$('#scroll').scrollTop(1000000);
Java Script:
document.getElementById('messages').scrollIntoView(false);
Scrolls to the last line of the content present.
My Scenario: I had an list of string, in which I had to append a string given by a user and scroll to the end of the list automatically. I had fixed height of the display of the list, after which it should overflow.
I tried #Jeremy Ruten's answer, it worked, but it was scrolling to the (n-1)th element. If anybody is facing this type of issue, you can use setTimeOut() method workaround. You need to modify the code to below:
setTimeout(() => {
var objDiv = document.getElementById('div_id');
objDiv.scrollTop = objDiv.scrollHeight
}, 0)
Here is the StcakBlitz link I have created which shows the problem and its solution : https://stackblitz.com/edit/angular-ivy-x9esw8
If your project targets modern browsers, you can now use CSS Scroll Snap to control the scrolling behavior, such as keeping any dynamically generated element at the bottom.
.wrapper > div {
background-color: white;
border-radius: 5px;
padding: 5px 10px;
text-align: center;
font-family: system-ui, sans-serif;
}
.wrapper {
display: flex;
padding: 5px;
background-color: #ccc;
border-radius: 5px;
flex-direction: column;
gap: 5px;
margin: 10px;
max-height: 150px;
/* Control snap from here */
overflow-y: auto;
overscroll-behavior-y: contain;
scroll-snap-type: y mandatory;
}
.wrapper > div:last-child {
scroll-snap-align: start;
}
<div class="wrapper">
<div>01</div>
<div>02</div>
<div>03</div>
<div>04</div>
<div>05</div>
<div>06</div>
<div>07</div>
<div>08</div>
<div>09</div>
<div>10</div>
</div>
You can use the HTML DOM scrollIntoView Method like this:
var element = document.getElementById("scroll");
element.scrollIntoView();
Javascript or jquery:
var scroll = document.getElementById('messages');
scroll.scrollTop = scroll.scrollHeight;
scroll.animate({scrollTop: scroll.scrollHeight});
Css:
.messages
{
height: 100%;
overflow: auto;
}
Using jQuery, scrollTop is used to set the vertical position of scollbar for any given element. there is also a nice jquery scrollTo plugin used to scroll with animation and different options (demos)
var myDiv = $("#div_id").get(0);
myDiv.scrollTop = myDiv.scrollHeight;
if you want to use jQuery's animate method to add animation while scrolling down, check the following snippet:
var myDiv = $("#div_id").get(0);
myDiv.animate({
scrollTop: myDiv.scrollHeight
}, 500);
I have encountered the same problem, but with an additional constraint: I had no control over the code that appended new elements to the scroll container. None of the examples I found here allowed me to do just that. Here is the solution I ended up with .
It uses Mutation Observers (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) which makes it usable only on modern browsers (though polyfills exist)
So basically the code does just that :
var scrollContainer = document.getElementById("myId");
// Define the Mutation Observer
var observer = new MutationObserver(function(mutations) {
// Compute sum of the heights of added Nodes
var newNodesHeight = mutations.reduce(function(sum, mutation) {
return sum + [].slice.call(mutation.addedNodes)
.map(function (node) { return node.scrollHeight || 0; })
.reduce(function(sum, height) {return sum + height});
}, 0);
// Scroll to bottom if it was already scrolled to bottom
if (scrollContainer.clientHeight + scrollContainer.scrollTop + newNodesHeight + 10 >= scrollContainer.scrollHeight) {
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}
});
// Observe the DOM Element
observer.observe(scrollContainer, {childList: true});
I made a fiddle to demonstrate the concept :
https://jsfiddle.net/j17r4bnk/
Found this really helpful, thank you.
For the Angular 1.X folks out there:
angular.module('myApp').controller('myController', ['$scope', '$document',
function($scope, $document) {
var overflowScrollElement = $document[0].getElementById('your_overflow_scroll_div');
overflowScrollElement[0].scrollTop = overflowScrollElement[0].scrollHeight;
}
]);
Just because the wrapping in jQuery elements versus HTML DOM elements gets a little confusing with angular.
Also for a chat application, I found making this assignment after your chats were loaded to be useful, you also might need to slap on short timeout as well.
Like you, I'm building a chat app and want the most recent message to scroll into view. This ultimately worked well for me:
//get the div that contains all the messages
let div = document.getElementById('message-container');
//make the last element (a message) to scroll into view, smoothly!
div.lastElementChild.scrollIntoView({ behavior: 'smooth' });
small addendum: scrolls only, if last line is already visible. if scrolled a tiny bit, leaves the content where it is (attention: not tested with different font sizes. this may need some adjustments inside ">= comparison"):
var objDiv = document.getElementById(id);
var doScroll=objDiv.scrollTop>=(objDiv.scrollHeight-objDiv.clientHeight);
// add new content to div
$('#' + id ).append("new line at end<br>"); // this is jquery!
// doScroll is true, if we the bottom line is already visible
if( doScroll) objDiv.scrollTop = objDiv.scrollHeight;
Just as a bonus snippet. I'm using angular and was trying to scroll a message thread to the bottom when a user selected different conversations with users. In order to make sure that the scroll works after the new data had been loaded into the div with the ng-repeat for messages, just wrap the scroll snippet in a timeout.
$timeout(function(){
var messageThread = document.getElementById('message-thread-div-id');
messageThread.scrollTop = messageThread.scrollHeight;
},0)
That will make sure that the scroll event is fired after the data has been inserted into the DOM.
This will let you scroll all the way down regards the document height
$('html, body').animate({scrollTop:$(document).height()}, 1000);
You can also, using jQuery, attach an animation to html,body of the document via:
$("html,body").animate({scrollTop:$("#div-id")[0].offsetTop}, 1000);
which will result in a smooth scroll to the top of the div with id "div-id".
Scroll to the last element inside the div:
myDiv.scrollTop = myDiv.lastChild.offsetTop
You can use the Element.scrollTo() method.
It can be animated using the built-in browser/OS animation, so it's super smooth.
function scrollToBottom() {
const scrollContainer = document.getElementById('container');
scrollContainer.scrollTo({
top: scrollContainer.scrollHeight,
left: 0,
behavior: 'smooth'
});
}
// initialize dummy content
const scrollContainer = document.getElementById('container');
const numCards = 100;
let contentInnerHtml = '';
for (let i=0; i<numCards; i++) {
contentInnerHtml += `<div class="card mb-2"><div class="card-body">Card ${i + 1}</div></div>`;
}
scrollContainer.innerHTML = contentInnerHtml;
.overflow-y-scroll {
overflow-y: scroll;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="d-flex flex-column vh-100">
<div id="container" class="overflow-y-scroll flex-grow-1"></div>
<div>
<button class="btn btn-primary" onclick="scrollToBottom()">Scroll to bottom</button>
</div>
</div>
Css only:
.scroll-container {
overflow-anchor: none;
}
Makes it so the scroll bar doesn't stay anchored to the top when a child element is added. For example, when new message is added at the bottom of chat, scroll chat to new message.
Why not use simple CSS to do this?
The trick is to use display: flex; and flex-direction: column-reverse;
Here is a working example. https://codepen.io/jimbol/pen/YVJzBg
A very simple method to this is to set the scroll to to the height of the div.
var myDiv = document.getElementById("myDiv");
window.scrollTo(0, myDiv.innerHeight);
On my Angular 6 application I just did this:
postMessage() {
// post functions here
let history = document.getElementById('history')
let interval
interval = setInterval(function() {
history.scrollTop = history.scrollHeight
clearInterval(interval)
}, 1)
}
The clearInterval(interval) function will stop the timer to allow manual scroll top / bottom.
I know this is an old question, but none of these solutions worked out for me. I ended up using offset().top to get the desired results. Here's what I used to gently scroll the screen down to the last message in my chat application:
$("#html, body").stop().animate({
scrollTop: $("#last-message").offset().top
}, 2000);
I hope this helps someone else.
I use the difference between the Y coordinate of the first item div and the Y coordinate of the selected item div. Here is the JavaScript/JQuery code and the html:
function scrollTo(event){
// In my proof of concept, I had a few <button>s with value
// attributes containing strings with id selector expressions
// like "#item1".
let selectItem = $($(event.target).attr('value'));
let selectedDivTop = selectItem.offset().top;
let scrollingDiv = selectItem.parent();
let firstItem = scrollingDiv.children('div').first();
let firstItemTop = firstItem.offset().top;
let newScrollValue = selectedDivTop - firstItemTop;
scrollingDiv.scrollTop(newScrollValue);
}
<div id="scrolling" style="height: 2rem; overflow-y: scroll">
<div id="item1">One</div>
<div id="item2">Two</div>
<div id="item3">Three</div>
<div id="item4">Four</div>
<div id="item5">Five</div>
</div>
Related
Hi I just added Google's No CAPTCHA reCAPTCHA to my website, and I am running into a small little issue. It does NOT fit on my mobile website, and that is a HUGE issue. I have tried everything such as:
HTML
<div id="captchadisplay">
<div class="g-recaptcha" data-sitekey="???"></div>
</div>
CSS
#captchadisplay {
width: 50% !important;
}
and
CSS
.g-recaptcha {
width: 50%;
}
Yet I can not seem to shrink it down for my mobile website. Any ideas? :)
By using the CSS transform property you can achieve changing the width by changing the entire scale of the reCAPTCHA.
By adding in just two inline styles, you can make the reCAPTCHA fit nicely on your mobile device:
<div class="g-recaptcha"
data-theme="light"
data-sitekey="XXXXXXXXXXXXX"
style="transform:scale(0.77);-webkit-transform:scale(0.77);transform-origin:0 0;-webkit-transform-origin:0 0;">
</div>
More details can be found on my site: https://www.geekgoddess.com/how-to-resize-the-google-nocaptcha-recaptcha/
I successfully implemented Geek Goddess' solution. The main issue with it is that it may not work on all browsers. Now, however, there is a simple solution provided by Google.
With reCAPTCHA version 2.0, there are new rules for the display of the widget and Google added tag attributes that change the way it is rendered.
The tag data-size can take the values of "normal", which is the default, and "compact", which fits in mobile device screens. This is what the compact widget looks like.
It is not the best looking widget, but it fits with less work than the other solutions.
For more attributes, check Google's reCAPTCHA v2.0 documentation
I have been using some JQuery, since putting transform(0.77) in the style attribute wasn't a truly responsive solution.
I add this media query in my CSS, with the max-width being the threshold where the ReCaptcha box is considered too large once passed:
#media(max-width: 390px) {
.g-recaptcha {
margin: 1px;
}
}
I then add this JQuery:
$(window).resize(function() {
var recaptcha = $(".g-recaptcha");
if(recaptcha.css('margin') == '1px') {
var newScaleFactor = recaptcha.parent().innerWidth() / 304;
recaptcha.css('transform', 'scale(' + newScaleFactor + ')');
recaptcha.css('transform-origin', '0 0');
}
else {
recaptcha.css('transform', 'scale(1)');
recaptcha.css('transform-origin', '0 0');
}
});
The 304 I use is the default width of the ReCaptcha box if unstyled.
Now the ReCaptcha will properly scale down no matter how small its parent container becomes, and it will behave as if it has a maximum width at its original width.
Note that the media query is simply a mechanism to detect a screen size change.
According to the documentation from Google shows a data-size attribute which can be set and this worked for me.
<div class="g-recaptcha" data-sitekey="XXXXXXXX" data-size="compact"></div>
But, the answer from #GeekGoddess provides a little more flexibility in sizing.
For me the compact mode implementation of Google re-captcha 2.0 is just lame. It looks ugly.
Just expanding from "Geek Goddess" solution.
You can do the following:
<div class="g-recaptcha" data-sitekey="..." style="-moz-transform:scale(0.77); -ms-transform:scale(0.77); -o-transform:scale(0.77); -moz-transform-origin:0; -ms-transform-origin:0; -o-transform-origin:0; -webkit-transform:scale(0.77); transform:scale(0.77); -webkit-transform-origin:0 0; transform-origin:0; filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.77,M12=0,M21=0,M22=0.77,SizingMethod='auto expand');"></div>
That will resize on almost all browsers IE, Chrome, FF, Opera (DXImageTransform is for IE <= 8).
Furthermore we can make it responsive by combining this transform scale with CSS max-width.
It's not the perfect way, but until we get the proper responsive fix from Google.
If you don't like the CSS solution, you may try the JS.
The idea is to dynamically switch between compact and normal mode of the recaptcha plugin.
I will provide an example with jQuery onboard, but it shouldn't be much to port it to pure JS.
I assume you have following HTML code on the site.
<div>
<div class="g-recaptcha" data-sitekey="[your-key-here]"></div>
</div>
Firstly you need to load gRecaptcha 2 explicitly and provide onload callback:
<script type='text/javascript' src='https://www.google.com/recaptcha/api.js?hl=en&onload=recaptchaCallback&render=explicit'>
Next, create your callback function which will also be your javascript media query.
function recaptchaCallback()
{
var mq = window.matchMedia("(max-width: 400px)");
mq.addListener(recaptchaRenderer);
recaptchaRenderer(mq);
}
The last thing is to render the recaptcha widget.
function recaptchaRenderer(mq)
{
var recaptcha = $('.g-recaptcha').eq(0);
var data = recaptcha.data();
var parent = recaptcha.parent();
recaptcha.empty().remove();
var recaptchaClone = recaptcha.clone();
parent.append(recaptchaClone);
recaptchaClone.data(data);
var options = {
'sitekey': data['sitekey'],
'size': 'compact'
};
if(!mq.matches)
{
options['size'] = 'normal';
}
grecaptcha.render(recaptchaClone.get(0), options);
}
You may wonder why I empty the div and clone all the g-recaptcha content. It's because gRecaptcha 2 wouldn't let you render second time to the same element. There could be a better way, but it's all I found for now.
Hope this works for you.
<div class="g-recaptcha" data-theme="light" data-sitekey="XXXXXXXXXXXXX" style="transform:scale(0.77);transform-origin:0 0"></div>
Just add style="transform:scale(0.77);transform-origin:0 0"
For who might be interested, I changed a little AjaxLeung solution and came up with this:
function resizeReCaptcha() {
if ($(".g-recaptcha").length) {
var recaptcha = $(".g-recaptcha");
recaptcha.parent().addClass('col-xs-12 padding0');
var innerWidth = recaptcha.parent().innerWidth();
if (innerWidth < 304) {
var newScaleFactor = innerWidth / 304;
recaptcha.css('transform', 'scale(' + newScaleFactor + ')');
recaptcha.css('-webkit-transform', 'scale(' + newScaleFactor + ')');
recaptcha.css('transform-origin', '0 0');
recaptcha.css('-webkit-transform-origin', '0 0');
} else {
recaptcha.css('transform', 'scale(1)');
recaptcha.css('-webkit-transform', 'scale(1)');
recaptcha.css('transform-origin', '0 0');
recaptcha.css('-webkit-transform-origin', '0 0');
}
}
}
$(window).resize(function() {
resizeReCaptcha();
});
$(document).ready(function () {
resizeReCaptcha();
});
Here's my spin on the resize:
<script>
function resizeReCaptcha() {
var width = $( ".g-recaptcha" ).parent().width();
if (width < 302) {
var scale = width / 302;
} else {
var scale = 1;
}
$( ".g-recaptcha" ).css('transform', 'scale(' + scale + ')');
$( ".g-recaptcha" ).css('-webkit-transform', 'scale(' + scale + ')');
$( ".g-recaptcha" ).css('transform-origin', '0 0');
$( ".g-recaptcha" ).css('-webkit-transform-origin', '0 0');
};
$( document ).ready(function() {
$( window ).on('resize', function() {
resizeReCaptcha();
});
resizeReCaptcha();
});
</script>
Unfortunately, NoCaptcha uses an iframe so at most you can control the height/width and use overflow:hidden; to cut off the excess. I would not recommend cutting off more than a few pixels of the Captcha for best usability.
Example:
.g-recaptcha {
max-width: 300px;
overflow: hidden;
}
On my site the re-captcha was getting cut off and looked bad.
After some experimentation I was able to fix the cutoff issue with this style update:
<style>
.g-recaptcha>div>div>iframe {
width: 380px;
height: 98px;
}
</style>
Hope you find this useful
#media only screen and (max-width : 480px) {
.smallcaptcha{
transform:scale(0.75);
transform-origin:50% 50%;
}
}
<div class="g-recaptcha" data-theme="light" data-sitekey="your site key" style="transform:scale(0.77);-webkit-transform:scale(0.77);transform-origin:0 0;-webkit-transform-origin:0 0;"></div>
This working for me, you try it..
<div class="g-recaptcha" data-theme="dark"></div>
I want to put the div behind the scrolling header like it is for the footer.
The footer is
#rt-footer-surround {
color: #686868;
background-color: #2E244E;
height: 40px;
width: 100%;
z-index: 900;
bottom: 0;
left: 0;
padding: 10px;
position: fixed;
}
but I cannot replicate it for the header.
the site in question is here:
site with z-index issue
To use the z-index style, you must also use either position:fixed;, position:absolute;, ,or position:relative; on the same object you wish to style.
Then, you can simply use a div to represent your header, footer, and main content section as follows:
<div class="head"></div>
<div class="mainbody"></div>
<div class="foot"></div>
Or alternatively, you can use the <head>,<main> and <footer> tags instead of divs. As far as coding and visuals are concerned, there is no difference.
Also, you don't have to put a massive number on the z-index. As long as one element's z-index is greater than another one's, that element will always be layered above, whether it is 900 over 1, or 2 over 1.
Ok here is what I came up with to solve the problem. Jquery.
Essentially my question was asking for this in the first place.
If you have content in a div you can place a nav bar in that div as a position:relative i.e. relative to that div.
What you cannot do via css is have the content in that div scroll up and stay underneath the nav bar you created. Furthermore when the nav menu area scrolls beyond the top of the screen it will then disappear.
So the jquery code I used does two things. It allows you to take a nav menu bar i.e. width 600px / height 50px and place it in its relative position anywhere you like. Furthermore, when it reachs the top of a users screen it will stop/halt and allow that to be the menu that is visible while everything else scrolls underneath that menu area.
Now, I don't think this is anything really new from Jquery but what is ultra convenient is that you can define a menu nav bar in any div position you want. Have a regular menu at the top and another menu perhaps below a slider or some content further down the page.
I will share the code if that is ok with SO... I paid for it myself.
Oh and here are two websites I have employed it on.
http://isaerudition.com/study-pages &
This is for a client I am preparing his website...
// JavaScript Document
/* jQuery(document).ready(function(){
if(jQuery('header,div,p,span,h1,h2,h3,h4,a').hasClass('isa-scroll-fixed')){
var el = jQuery('.isa-scroll-fixed'),
elTop = jQuery(el).offset().top;
elLeft = jQuery(el).offset().left;
//alert(elTop);
jQuery(document).scroll(function(){
var height = jQuery(window).height();
var scrollTop = jQuery(window).scrollTop();
if(scrollTop>=elTop){
//add fixed
jQuery(el).addClass('scroll_fixed').css("left",elLeft+"px");
}else{
//clear fixed
jQuery(el).removeClass('scroll_fixed').attr('style','');
}
})
}
})
*/
// JavaScript Document
/* jQuery(window).load(function(){
if(jQuery('header,div,p,span,h1,h2,h3,h4,a').hasClass('isa-scroll-fixed')){
var el = jQuery('.isa-scroll-fixed'),
elTop = jQuery(el).offset().top;
elLeft = jQuery(el).offset().left;
//alert(elTop);
var scrollTop = jQuery(window).scrollTop();
scrollFixed(el,elTop,elLeft);
}
}) */
var setInter = null;
var session = null;
setInter = setInterval(function(){
if(jQuery('header,div,p,span,h1,h2,h3,h4,a').hasClass('isa-scroll-fixed')){
var el = jQuery('.isa-scroll-fixed');
session = jQuery(el).attr('set-scroll');
//alert(session);
if(session == '2'){
jQuery(el).attr('set-scroll','2');
}else{
jQuery(el).attr('set-scroll','1');
}
if(session == '1'){
setValue(el);
}
}
}, 200);
function setValue(el){
var setScroll = jQuery(el).attr('set-scroll');
elTop = jQuery(el).offset().top;
elLeft = jQuery(el).offset().left;
//alert(elTop);
jQuery(el).attr('set-scroll','2');
scrollFixed(el,elTop,elLeft);
};
function scrollFixed(el,elTop,elLeft){
jQuery(document).unbind('scroll').scroll(function(){
//alert(elTop);
var height = jQuery(window).height();
var scrollTop = jQuery(window).scrollTop();
if(scrollTop>=elTop){
//add fixed
jQuery(el).addClass('scroll_fixed').css("left",elLeft+"px");
}else{
//clear fixed
jQuery(el).removeClass('scroll_fixed').attr('style','');
}
})
}
I'm using <a href> element along with :target css selector to show a <div> which by default is set to display:none. Problem is, that when I click on the link to show that <div>, it is automatically scrolling down my site towards that <div>.
Is there a way to stop the screen movement?
Unfortunately I am not yet proficient in anything besides CSS and HTML.
You can use event.preventDefault() to avoid this. Something like this:
$('a.yourclass').click(function(e)
{
//your code
e.preventDefault();
});
OR:
link
in the link enter:
Link here
You'll need JS anyway:
// (in jQuery)
$el.on('click', function(e) {
// find current scroll position
var pos = document.body.scrollTop || document.documentElement.scrollTop;
// let normal action propagate etc
// in the next available frame (async, hence setTimeout), reset scroll posiion
setTimeout(function() {
window.scrollTo(0, pos);
}, 1);
})
I don't know if this will flicker the screen. It might. It's a horrible hack either way.
In my Chrome, there's no flicker: http://jsfiddle.net/rudiedirkx/LEwNd/1/show/
There are two ways to tell the browser we don't want it to act:
The main way is to use the event object. There's a method
event.preventDefault().
If the handler is assigned using on (not by
addEventListener), then we can just return false from it.
Example:
Click here
or
here
This is a bit of a hack but you could use a basic css work around:
CSS only Example
#div1 {
height: 0;
overflow:hidden;
}
#div1:target {
height: auto;
margin-top: -110px;
padding-top: 110px;
}
#div2 {
background:red;
}
Click to show
<div id="div1">
<div id="div2">Content</div>
</div>
If you need it to be a little more flexible you can add some js...
More Flexible Example with JS
$('a').click(function () {
$('#div1').css({
'margin-top': 0 - $('#div1').position().top + $(window).scrollTop(),
'padding-top': $('#div1').position().top - $(window).scrollTop()
});
});
Basically you're pulling the top of div1 up with the negative margin and then pushing div2 back down with the padding, so that the top of div1 rests at the top of the window... Like I said its a hack but it does the trick.
Those links are anchor-links and by default made for those jumps :) You could use JS to prevent the default behaviour in some way. For example using jQuery:
$('a').click(function(e){e.preventDefault();});
or by default add return false; to the links
Avoid using :target all together and just use onclick event.
function myFunction()
{
document.getElementById('hiddenDiv').style.display = 'block';
return false;
}
.qsf-demo-canvas
{ max-width: 100%;
max-height:600px;
overflow:scroll;}
Is it possible to center the horizontal scrollbar with an overflow:scroll div.
If the content was much wider than the available space the div content would be centred by default?
The user should still be able to scroll though.
thankyou
In JS it's possible :
this scrolls the internal scroll of a div to it's horizontal middle
var myDiv = $("#Mydiv");
var scrollto = myDiv.offset().left + (myDiv.width() / 2);
myDiv.animate({ scrollLeft: scrollto});
I hope that this will help you.
I had success with:
jQuery(document).ready(function() {
jQuery(window).resize(function() {
var myDiv = jQuery("#myDiv"),
myChild = myDiv.find("> *:first-child");
myDiv.animate({
scrollLeft: (myChild.width() - myDiv.width()) / 2
}, {
duration: 0
});
});
jQuery(window).resize();
});
Some optimization - change animate to scrollLeft(). Works with jQuery.slim and according to Chrome DevTools, is much faster.
var myDiv = $("#Mydiv");
var scrollto = myDiv.offset().left + (myDiv.width() / 2);
myDiv.scrollLeft(scrollto);
The issue:
Some of the items in the select require more than the specified width of 145px in order to display fully.
Firefox behavior: clicking on the select reveals the dropdown elements list adjusted to the width of the longest element.
IE6 & IE7 behavior: clicking on the select reveals the dropdown elements list restricted to 145px width making it impossible to read the longer elements.
The current UI requires us to fit this dropdown in 145px and have it host items with longer descriptions.
Any advise on resolving the issue with IE?
The top element should remain 145px wide even when the list is expanded.
Thank you!
The css:
select.center_pull {
background:#eeeeee none repeat scroll 0 0;
border:1px solid #7E7E7E;
color:#333333;
font-size:12px;
margin-bottom:4px;
margin-right:4px;
margin-top:4px;
width:145px;
}
Here's the select input code (there's no definition for the backend_dropbox style at this time)
<select id="select_1" class="center_pull backend_dropbox" name="select_1">
<option value="-1" selected="selected">Browse options</option>
<option value="-1">------------------------------------</option>
<option value="224">Option 1</option>
<option value="234">Longer title for option 2</option>
<option value="242">Very long and extensively descriptive title for option 3</option>
</select>
Full html page in case you want to quickly test in a browser:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>dropdown test</title>
<style type="text/css">
<!--
select.center_pull {
background:#eeeeee none repeat scroll 0 0;
border:1px solid #7E7E7E;
color:#333333;
font-size:12px;
margin-bottom:4px;
margin-right:4px;
margin-top:4px;
width:145px;
}
-->
</style>
</head>
<body>
<p>Select width test</p>
<form id="form1" name="form1" method="post" action="">
<select id="select_1" class="center_pull backend_dropbox" name="select_1">
<option value="-1" selected="selected">Browse options</option>
<option value="-1">------------------------------------</option>
<option value="224">Option 1</option>
<option value="234">Longer title for option 2</option>
<option value="242">Very long and extensively descriptive title for option 3</option>
</select>
</form>
</body>
</html>
For IE 8 there is a simple pure css-based solution:
select:focus {
width: auto;
position: relative;
}
(You need to set the position property, if the selectbox is child of a container with fixed width.)
Unfortunately IE 7 and less do not support the :focus selector.
I did Google about this issue but didn't find any best solution ,So Created a solution that works fine in all browsers.
just call badFixSelectBoxDataWidthIE() function on page load.
function badFixSelectBoxDataWidthIE(){
if ($.browser.msie){
$('select').each(function(){
if($(this).attr('multiple')== false){
$(this)
.mousedown(function(){
if($(this).css("width") != "auto") {
var width = $(this).width();
$(this).data("origWidth", $(this).css("width"))
.css("width", "auto");
/* if the width is now less than before then undo */
if($(this).width() < width) {
$(this).unbind('mousedown');
$(this).css("width", $(this).data("origWidth"));
}
}
})
/* Handle blur if the user does not change the value */
.blur(function(){
$(this).css("width", $(this).data("origWidth"));
})
/* Handle change of the user does change the value */
.change(function(){
$(this).css("width", $(this).data("origWidth"));
});
}
});
}
}
Here is a little script that should help you out:
http://www.icant.co.uk/forreview/tamingselect/
For a simple Javascript-free solution, adding a title-attribute to your <option>s holding the text might be enough, depending on your requirements.
<option value="242" title="Very long and extensively descriptive text">
Very long and extensively descriptive text
</option>
This will show the cut-off text in a tool-tip fashion on hovering the <option>, regardless of the width of the <select>.
Works for IE7+.
Not javascript free i'm afraid, but I managed to make it quite small using jQuery
$('#del_select').mouseenter(function () {
$(this).css("width","auto");
});
$('#del_select').mouseout(function () {
$(this).css("width","170px");
});
Simply you can use this plugin for jquery ;)
http://plugins.jquery.com/project/skinner
$(function(){
$('.select1').skinner({'width':'200px'});
});
Small, but hopefully useful update to the code from MainMa & user558204 (thanks guys), which removes the unnecessary each loop, stores a copy of $(this) in a variable in each event handler as it's used more than once, also combined the blur & change events as they had the same action.
Yes, it's still not perfect as it resizes the select element, rather than just the drop-down options. But hey, it got me out of a pickle, I (very, very unfortunately) still have to support an IE6-dominant user base across the business.
// IE test from from: https://gist.github.com/527683
var ie = (function () {
var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
} ());
function badFixSelectBoxDataWidthIE() {
if (ie < 9) {
$('select').not('[multiple]')
.mousedown(function() {
var t = $(this);
if (t.css("width") != "auto") {
var width = t.width();
t.data("ow", t.css("width")).css("width", "auto");
// If the width is now less than before then undo
if (t.width() < width) {
t.unbind('mousedown');
t.css("width", t.data("ow"));
}
}
})
//blur or change if the user does change the value
.bind('blur change', function() {
var t = $(this);
t.css("width", t.data("ow"));
});
}
}
A different approach:
instead of a select make it an edit box, disabled so noone can enter anything manually or change contents after selection
another hidden edit to contain an id of a selected option (explained below)
make a button [..] and script it to show that div below
make a hidden div with absolute position under or near the edit box
make that div to contain a select with style size="6" (to show 6 options and a scrollbar rather than a drop-down list) and a button "select" and maybe "cancel"
Do not style width so the whole thing will assume width of the widest option or the button plus maybe some padding of your choice
script the "select" button to copy id of the selected option to the hidden edit box and it's value to the visible one, also to hide the div again.
4 simple javascript commands total.
I found a pretty straightforward fix for this. In the <select> html element add these properties:
onmouseover="autoWidth(this)"
onblur="resetWidth(this)"
So whenever user clicks on that the width will automatically expand, and user moves out of the select box, the width will be reset to original.
similar solution can be found here using jquery to set the auto width when focus (or mouseenter) and set the orignal width back when blur (or mouseleave) http://css-tricks.com/select-cuts-off-options-in-ie-fix/.
for (i=1;i<=5;i++){
idname = "Usert" + i;
document.getElementById(idname).style.width = "100%";
}
I used this way to showed the drop down list when the width is not showed correctly.
It work for IE6, Firefox and Chrome.
A full fledged jQuery plugin is available, check out the demo page: http://powerkiki.github.com/ie_expand_select_width/
disclaimer: I coded that thing, patches welcome
Why would anyone want a mouse over event on a drop down list? Here's a way of manipulating IE8 for the way a drop down list should work:
First, let's make sure we are only passing our function in IE8:
var isIE8 = $.browser.version.substring(0, 2) === "8.";
if (isIE8) {
//fix me code
}
Then, to allow the select to expand outside of the content area, let's wrap our drop down lists in div's with the correct structure, if not already, and then call the helper function:
var isIE8 = $.browser.version.substring(0, 2) === "8.";
if (isIE8) {
$('select').wrap('<div class="wrapper" style="position:relative; display: inline-block; float: left;"></div>').css('position', 'absolute');
//helper function for fix
ddlFix();
}
Now onto the events. Since IE8 throws an event after focusing in for whatever reason, IE will close the widget after rendering when trying to expand. The work around will be to bind to 'focusin' and 'focusout' a class that will auto expand based on the longest option text. Then, to ensure a constant min-width that doesn't shrink past the default value, we can obtain the current select list width, and set it to the drop down list min-width property on the 'onchange' binding:
function ddlFix() {
var minWidth;
$('select')
.each(function () {
minWidth = $(this).width();
$(this).css('min-width', minWidth);
})
.bind('focusin', function () {
$(this).addClass('expand');
})
.change(function () {
$(this).css('width', minWidth);
})
.bind('focusout', function () {
$(this).removeClass('expand');
});
}
Lastly, make sure to add this class in the style sheet:
select:focus, select.expand {
width: auto;
}
Not javascript free, I am afraid too and my solution do require a js library, however, you can only use those files which you need rather than using them all, maybe best suited for those who are already using YUI for their projects or deciding which one to use. Have a look at: http://ciitronian.com/blog/programming/yui-button-mimicking-native-select-dropdown-avoid-width-problem/
My blog post also discusses other solutions as well, one is referenced back to here on stackoverflow, why I went back to create my own SELECT element is because of simple reason, I don't like mouseover expand events. Maybe if that helps anyone else too!
The jquery BalusC's solution improved by me. Used also: Brad Robertson's comment here.
Just put this in a .js, use the wide class for your desired combos and don't forge to give it an Id. Call the function in the onload (or documentReady or whatever).
As simple ass that :)
It will use the width that you defined for the combo as minimun length.
function fixIeCombos() {
if ($.browser.msie && $.browser.version < 9) {
var style = $('<style>select.expand { width: auto; }</style>');
$('html > head').append(style);
var defaultWidth = "200";
// get predefined combo's widths.
var widths = new Array();
$('select.wide').each(function() {
var width = $(this).width();
if (!width) {
width = defaultWidth;
}
widths[$(this).attr('id')] = width;
});
$('select.wide')
.bind('focus mouseover', function() {
// We're going to do the expansion only if the resultant size is bigger
// than the original size of the combo.
// In order to find out the resultant size, we first clon the combo as
// a hidden element, add to the dom, and then test the width.
var originalWidth = widths[$(this).attr('id')];
var $selectClone = $(this).clone();
$selectClone.addClass('expand').hide();
$(this).after( $selectClone );
var expandedWidth = $selectClone.width()
$selectClone.remove();
if (expandedWidth > originalWidth) {
$(this).addClass('expand').removeClass('clicked');
}
})
.bind('click', function() {
$(this).toggleClass('clicked');
})
.bind('mouseout', function() {
if (!$(this).hasClass('clicked')) {
$(this).removeClass('expand');
}
})
.bind('blur', function() {
$(this).removeClass('expand clicked');
})
}
}
Its tested in all version of IE, Chrome, FF & Safari
// JavaScript code
<script type="text/javascript">
<!-- begin hiding
function expandSELECT(sel) {
sel.style.width = '';
}
function contractSELECT(sel) {
sel.style.width = '100px';
}
// end hiding -->
</script>
// Html code
<select name="sideeffect" id="sideeffect" style="width:100px;" onfocus="expandSELECT(this);" onblur="contractSELECT(this);" >
<option value="0" selected="selected" readonly="readonly">Select</option>
<option value="1" >Apple</option>
<option value="2" >Orange + Banana + Grapes</option>
I've got yet another contribution to this. I wrote this a while back that you may find helpful: http://dpatrickcaldwell.blogspot.com/2011/06/giantdropdown-jquery-plugin-for-styling.html
It's a jquery plugin to make a styleable unordered list backed by the hidden select element.
The source is on github: https://github.com/tncbbthositg/GiantDropdown
You'd be able to handle behaviors and styles on the UL that you can't with the SELECT. Everything else should be the same because the select list is still there, it's just hidden but the UL will use it as a backing data store (if you will).
I wanted this to work with selects that I added dynamically to the page, so after a lot of experimentation, I ended up giving all the selects that I wanted to do this with the class "fixedwidth", and then added the following CSS:
table#System_table select.fixedwidth { width: 10em; }
table#System_table select.fixedwidth.clicked { width: auto; }
and this code
<!--[if lt IE 9]>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(document).on(
{
'mouseenter': function(event) {
jQuery(this).addClass('clicked');
},
'focusout change blur': function() {
jQuery(this).removeClass('clicked');
}
}, 'select.fixedwidth');
});
</script>
<![endif]-->
A couple of things to note:
In spite of the fact that my selects are all in a table, I had to do "on" to the jQuery(document).on instead of to jQuery('table#System_table').on
In spite of the fact that the jQuery documentation says to use "mouseleave" instead of "blur", I found that in IE7 when I moved the mouse down the drop down list, it would get a mouseleave event but not a blur.
Here is a solution that actually works.
It sets the width in IE and doesn't mess up your page layout and doesn't close the dropdown when you mouse over the select options like some of the other solutions on this page.
You will need however to change the margin-right value and width values to match what you have for your select fields.
Also you can replace the $('select') with $('#Your_Select_ID_HERE') to only effect a specific select field. As well you will need to call the function fixIESelect() on the body onload or via jQuery using DOM ready as I did in my code below:
//////////////////////////
// FIX IE SELECT INPUT //
/////////////////////////
window.fixIESelect_clickset = false;
function fixIESelect()
{
if ($.browser.msie)
{
$('select').mouseenter(function ()
{
$(this).css("width","auto");
$(this).css("margin-right","-100");
});
$('select').bind('click focus',function ()
{
window.fixIESelect_clickset = true;
});
$('select').mouseout(function ()
{
if(window.fixIESelect_clickset != true)
{
$(this).css("width","93px");
window.fixIESelect_clickset = false;
}
});
$('select').bind('blur change',function ()
{
$(this).css("width","93px");
});
}
}
/////////////
// ONLOAD //
////////////
$(document).ready(function()
{
fixIESelect();
});
For my layout, I didn't want a hack (no width increasing, no on click with auto and then coming to original). It broke my existing layout. I just wanted it to work normally like other browsers.
I found this to be exactly like that :-
http://www.jquerybyexample.net/2012/05/fix-for-ie-select-dropdown-with-fixed.html
A workaround if you don't care about the strange view after an option is selected (i.e. Select to jump to a new page):
<!-- Limit width of the wrapping div instead of the select and use 'overflow: hidden' to hide the right part of it. -->
<div style='width: 145px; overflow: hidden; border-right: 1px solid #aaa;'>
<select onchange='jump();'>
<!-- '▼(▼)' produces a fake dropdown indicator -->
<option value=''>Jump to ... ▼</option>
<option value='1'>http://stackoverflow.com/questions/682764/select-dropdown-with-fixed-width-cutting-off-content-in-ie</option>
...
</select>
</div>
A pure css solution : http://bavotasan.com/2011/style-select-box-using-only-css/
.styled-select select {
background: transparent;
width: 268px;
padding: 5px;
font-size: 16px;
line-height: 1;
border: 0;
border-radius: 0;
height: 34px;
-webkit-appearance: none;
}
.styled-select {
width: 240px;
height: 34px;
overflow: hidden;
background: url(http://cdn.bavotasan.com/wp-content/uploads/2011/05/down_arrow_select.jpg) no-repeat right #ddd;
border: 1px solid #ccc;
}
<div class="styled-select">
<select>
<option>Here is the first option</option>
<option>The second option</option>
</select>
</div>
Best solution: css + javascript
http://css-tricks.com/select-cuts-off-options-in-ie-fix/
var el;
$("select")
.each(function() {
el = $(this);
el.data("origWidth", el.outerWidth()) // IE 8 can haz padding
})
.mouseenter(function(){
$(this).css("width", "auto");
})
.bind("blur change", function(){
el = $(this);
el.css("width", el.data("origWidth"));
});