JQuery reproducing onmouseenter logic inline at element level - javascript

I have a very large HTML page whereby an enterprise user is displaying thousands of database records as part of a batch-update/validation process.
Within the page I need to add tooltips to many of the elements. Previously we have used the trusty approach of doing this in the <head>:
$("elementID").mouseenter(function(){
// tool tip logic
// goes here
});
The problem is that this is adding tens of thousands of lines of JavaScript and causing massive performance problems. So, I am researching the differences of applying this at element level instead. So rather than having the above code for each element that requires a tooltip, I am declaring a single script block like this:
function ShowTooltip(ctrl, tooltip) {
var o = $(ctrl).offset();
var y = o.top;
var x = o.left;
$("#ttfloat").css({ top: o.top, left: o.left });
$("#ttfloat").html(tooltip);
$("#ttfloat").show();
}
function HideToolTip() {
$("#ttfloat").hide();
}
And then firing this using the following approach for each respective element:
<div id="ttfloat"> </div>
<p>Tool tip <span id="lbl1" runat="server" onmouseover="ShowTooltip(this, 'Tip Text');" onmouseout="HideToolTip();">appears here</span></p>
The problem is that when hovering over the <span> elements, there is a flicker of the tooltip element as the browser fires onmouseover repeatedly. I read on other SO solutions that JQuery mouseenter is the way to go to solve this, but can only find examples that wire up the events in the head. Can it be done in-line in the element, or is there a better way altogether? The solution must work with older browsers and be standards compliant.
See JSFiddle

How about something like this:
<span data-tooltip-text="Tip text here">blah blah</span>
And then:
$("[data-tooltip-text]").on({
mouseenter : function() {
var o = $(this).offset();
var tooltip = $(this).attr("data-tooltip-text");
$("#ttfloat").css({ top: o.top, left: o.left })
.html(tooltip)
.show();
},
mouseleave : function() {
$("#ttfloat").hide();
}
});
Demo: http://jsfiddle.net/szCU2/2/
I'd suggest you offset the vertical position of the tooltip a little bit, so that it doesn't completely cover the element that you're hovering over (which is clunky looking, and can potentially cause a mouseleave event since the mouse is then over the tooltip):
o.top + 18; // or whatever offset works for you
Demo: http://jsfiddle.net/szCU2/3/

If the behavior is the same in all of them, you should use a class selector instead of an id selector and simply add that class to all of your divs. Then you just need that code once rather than having a copy of it for every single div. Store the data somewhere useful (like a custom attribute for the div) and use that in your code.
html:
<div id="blah" class="divWithTooltip" data-custom-attribute="some tooltip text">
javascript:
$('.divWithTooltip')
.on('mouseenter', function() {
someMethodToDoYourTooltipStuff( $(this).attr('data-custom-attribute') );
})
.on('mouseout', function() {
someMethodToHideYourTooltip();
});

Related

div onclick function to change body background image

I want a small picture that acts like a button, to be click-able with a function to change the body background-image. I am a total newbie and I'm trying to learn. The most simple way, I thought, would be to have a div with a background-image.
I have to use unsemantic grid, also.
So I pretty much only have the div with a background image. How do I write this function? I'm sure it's really easy and I've read like 20 threads here but none of them were useful for me
Edit: added my code
#knapp {
height:50px;
width:50px;
background-image:url(http://ingridwu.dmmdmcfatter.com/wp-content/uploads/2015/01/placeholder.png);
background-repeat:no-repeat;
background-size:contain;
position:absolute;
top:90vh;
right:3vw;
}
<div id="knapp" class="grid-10 prefix-90"></div>
Add cursor on the div to appear clickable
#knapp {
cursor: pointer;
}
You could put the new background-image in a new css rule
body.newbg {
background-image:url(path-to-new-background.png);
}
This is body with the old background-image
body {
background-image:url(path-to-old-background.png);
}
and with jquery just add/toggle the class by doing something like that (in $(document).ready()):
$('#knapp').on('click', function(){
$('body').addClass('newbg');
// you could instead do toggleClass if you want for each click to have background switch between old background and new background
});
This is a cleaner approach compared to all the other answers as it separates presentation (css), structure (html) and behavior (javascript).
This is because it doesn't use JavaScript to change style directly. Also it doesn't pollute html with onclick which is also a bad practice.
Here is a plunkr: https://plnkr.co/edit/aiGZmvvi6WWGFs7E9xTp
and here is one with a circular collection of backgrounds (thanks to Kai's idea)
https://plnkr.co/edit/0djmmNM9OOTdfYyvLvUH?p=preview
Create a button with onclick attribute with a function name like replace.
Defined the function in your script like:
function replace() {
document.body.style.backgroundImage = 'url(https://lh6.ggpht.com/8mgTDZXaLMS1JsnF28Tjh6dahHwN1FqcXCVnifkfppmNLqnD-mPBuf9C1sEWhlEbA4s=w300)';
}
Explanation:
You set the style property of the body (using document.body object) to other background-image.
If something is not clear, I will happy to explain.
Working example:
function replace() {
document.body.style.backgroundImage = 'url(https://lh6.ggpht.com/8mgTDZXaLMS1JsnF28Tjh6dahHwN1FqcXCVnifkfppmNLqnD-mPBuf9C1sEWhlEbA4s=w300)';
}
body {
background-image: url(http://www.julienlevesque.net/preview/google-smile-preview.jpg);
}
div {
background:blue;
color:#fff;
float:left;
}
<div onclick="replace()">Replace background-image</div>
This may help you...
$('.yourClassofDiv').click({
$(this).css("background-image",'url("' + URLofIMAGE+ '")')
});
Try using onclick at div#knapp element , set document.body.style.background to url of image file
#knapp {
height:50px;
width:50px;
background-image:url(http://lorempixel.com/50/50);
background-repeat:no-repeat;
background-size:contain;
position:absolute;
top:90vh;
right:3vw;
}
<div id="knapp" class="grid-10 prefix-90" onclick="document.body.style.background = 'url(http://lorempixel.com/'+ window.innerWidth + '/'+ window.innerHeight +') no-repeat'"></div>
here is a simple way in jquery
$(document).ready(function() {
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/detail-requiem.jpg)').css('background-repeat', 'no-repeat');
$('div').css('cursor', 'pointer').click(function() {
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/Requiem-Julien-Levesque.jpg)');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body>
<div style="background-color:yellow">Click Here to change background Image</div>
</body>
Here i will explain the code.
The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s).
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".
Here is what happen in the code.
1.
$(document).ready(function(){
// jQuery methods go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.
2
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/detail-requiem.jpg)').css('background-repeat', 'no-repeat');
getting the body element of your html and set its background-image with .css() action. which i gave it more one action
3
$('div').css('cursor', 'pointer').click(function() {
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/Requiem-Julien-Levesque.jpg)');
});
this is where the change takes place. i got the div to be clicked by $('div') and first gave it an action of changing the mouse to cursor to indicate its clickable and then gave it the click function, where our background-image get changed on click
If I understand the question, you should be able to create a variable in jQuery which is an array of all the string versions of your image urls that you want to use:
var images = ['../images/####','../images/$$$$', 'http://some.other/url.here];
// do this for as many images as you want to cycle through
Like that.
Then you can make a counter variable:
var counter = 0;
and set it to zero.
Next, add the event listener on() to your div like this:
$('#knapp').on('click', function(){
});
Finally, inside your event listener, change the CSS background-image property of the div to one of your images in the array:
// do this inside a document.ready() function
$('#knapp').on('click', function(){
$(this).css('background-image','url("' + images[counter] + '")');
counter++;
});
I hope this helped! Also, remember to increment counter
EDIT ----------------------------------------------------------------
OK, so I totally jumped over something obvious which is the fact that the counter might go too high and access something out of scope. To prevent this add the following inside of your on() listener:
if(counter >= images.length - 1){
counter = 0;
}
EDIT 2 --------------------------------------------------------------
Ok, so I didn't know what exactly you were asking at first, so here is my second answer. Since it seems like what you are actually trying to do is only switch the background image once on click, then you could use something like this:
$(document).ready(function(){
$('#knapp').on('click', function(){
$(this).css('background-image','url("YOUR_NEW_URL_HERE")');
});
});
or you could have it toggle between two images by making two identical classes in CSS (except for the background image) and replacing one with the other using .addClass and .removeClass.
EDIT 3---------------------------------------------------------------
I never thought I would edit this post this many times, but apparently I missed that the body background image should be changed (thanks to comments). My bad and thanks for pointing it out (even if you were talking to someone else).

Javascript niceScroll resize function

I am using jQuery plugin version 3.10 to use custom scrollbars. I have numerous horizontal slides and each uses its own custom scrollbar. I want to include javascript .onclick function that expands text. However, the scrollbar does not appear when I expand the text and it overflows. I am using the following code to select the headings which should have the onclick function (tag "h3", class "click"):
function toggleNext(el) {
var next=el.nextSibling;
while(next.nodeType != 1) next=next.nextSibling;
next.style.display=((next.style.display=="none") ? "block" : "none");
}
function getElementsByTagAndClassName(tag,cname) {
var tags=document.getElementsByTagName(tag);
var cEls=new Array();
for (i=0; i<tags.length; i++) {
var rE = new RegExp("(^|\s)" + cname + "(\s|$)");
if (rE.test(tags[i].className)) {
cEls.push(tags[i]);
}
}
return cEls;
}
function toggleNextByTagAndClassName(tag,cname) {
var ccn="clicker";
clickers=getElementsByTagAndClassName(tag,cname);
for (i=0; i<clickers.length; i++) {
clickers[i].className+=" "+ccn;
clickers[i].onclick=function() {toggleNext(this)}
toggleNext(clickers[i]);
}
}
window.onload=function(){toggleNextByTagAndClassName('h3','click')}
Example of HTML:
<article class="slide" id="lorem">
<div class="inner">
<h3 class="click">Lorem Ipsum</h3>
<div class="content">
<p>Sample text, is sample text, is sample text</p>
</div>
I know from previous research that I've done that I have to call the resize function from niceScroll jQuery plugin, which is as follows.
$(name-of-div).getNiceScroll().resize()
I have tried using the resize function with the name-of-div as content, however this does not yield the expected results. Please help if you can. I am not sure how to implement the two together.
Not sure if understood what's going on but I had a similar problem. Try using the resize() inside a setTimeout.
Note that the "name-of-div" must be the name of the scroll's container.
The jQuery code would looks like:
setTimeout(function(){
$('name-of-div').getNiceScroll().resize()
}, 500);
I used 500 as an example, but if your div's text expand while animate you must use a number greater then your div animation, and of course, the code must execute after all interactions
See the question below. There are two answers and both work for me. Basically, I have applied the second method(See the second answer) suggested there. Because, it works instantly and the first method doesn't seem to work instantly after the div has been resized.
Jquery Nice scroll not working

Prevent position absolute element from sticking inside scrollable div

Having this issue with multiple items (e.g. a color picker, date picker, and a time picker) where when they pop out and are thus positioned absolute relative to the input, if a user scrolls the newly spawned element also moves with it.
Based on the nature of most plugins (all major bootstrap plugins I've noticed do this) I'm trying to think of a way to target and keep these elements fixed relative to their original location without hacking every plugin if possible.
Below is an example of the issue in which I utilized the bootstrap datepicker. Click on input to spawn datepicker and then scroll and notice the datepicker staying relative to the screen not the input.
Link to JSFiddle: http://jsfiddle.net/GuJR6/1/
Thanks!
.container {
margin-top: 15px;
height:400px;
overflow-y: scroll;
}
.scrolling-content {
height:1000px;
}
<div class="container">
<div class="scrolling-content">
<div class="well text-center">
<input type="text" class="datetimepicker" readonly>
</div>
</div>
</div>
$(".datetimepicker").datetimepicker({format: 'yyyy-mm-dd hh:ii'});
I just forked bootstrap-datetimepicker and added the container option mention by Jan Peapke. You can use it like this:
$(selector).datetimepicker({ container: nativeDOMElement });
$(selector).datetimepicker({ container: jQueryObject });
$(selector).datetimepicker({ container: jQuerySelector });
This allows you to solve your problem:
In your css:
.scrolling-content {
position: relative;
}
Compare: CSS-Tricks
js
$(".datetimepicker").datetimepicker({
format: 'yyyy-mm-dd hh:ii',
container: '.scrolling-content'
});
Fiddle
http://jsfiddle.net/marionebl/GuJR6/2/
The first input in the fiddle applies the explained fix for your issue. The second should behave like before.
Related pull request
https://github.com/smalot/bootstrap-datetimepicker/pull/215
I'm afraid the problem lies with the bootstrap datetimepicker itself.
Instead of attaching it to the same container as the input, it is attached to the body.
I looked up the documentation to see if there is an option to set the parent, but I'm afraid there is not.
As a solution you could try another framework, like jQueryUI or this plugin.
You could also try to correct the position of the picker manually by attaching a click handler to the input field that removes the datepicker from the body, adds it to the content of the scrollcontainer and uses the events mouse coordinates to position it correctly inside the container. Seems like a lot of hassle though. :)
regards,
J
$('YOURCLASSNAME').on('scroll', function () {
var $this = $('.input-group.date');
$this.datepicker('place');
});
Add above code before
Datepicker.prototype = {...}
This is the solution. and works fine on all devices and screen sizes
Even i have been facing this issue.
Found out a solution to this By adding var t;
$('YOURCLASSNAME').on('scroll', function () {
var $this = $('.input-group.date');
window.clearTimeout(t);
t = window.setTimeout(function () {
$this.datepicker('place');
}, 50)
});
Add above code after if (showFocus) this.show();
in this block
var Datepicker = function (element, options) {....} of bootstrap-datepicker.js plugin

NicEdit - Unbind Events

I decided to use NicEdit on a project, because is lightweight.
So, now I have a variable number of instances in my page, loaded on click and removed on editor blur.
I need to know how to unbind events from this component. I tried to unbind it manually, but I didn't understand where they are linked!
$('.container').bind('click', function(){
var _form = $(this).parentsUntil('form').parent();
var textarea = _form.find('textarea.edit');
var ta_id = textarea.attr('id');
var ed = new nicEditor(niceditOptions).panelInstance(ta_id);
// Show Preview and update textarea and so on
ed.addEvent('blur', function() {
var _ed = nicEditors.findEditor(ta_id);
var ev_type, evt, events = this.eventList;
for (ev_type in events){
for (evt in ev_type){
if (this.removeEventListener){
this.removeEventListener(ev_type, events[ev_type][evt]);
}
else {
this.detachEvent('on' + ev_type, events[ev_type][evt]);
}
}
}
this.removeInstance(ta_id);
});
});
There are potentially other ways of going about your solution, but in this scenario I prefer to use one version of a nicEditor panel and bind all of my WYSIWYG instances. The reason for this is that I think its slightly tidier. I will assume that you know how to bind one editor to multiple editable instances.
On load my HTML would probably look something like this:
<div id="instance1">text</div>
...
<div id="instance2">text</div>
...
<div id="myNicPanel" style="display:none;position:relative;"></div>
So, once the page has completed it's load cycle, i should have two editable areas and a hidden editor. I would then use the following jQuery to reposition and show the editor when an instance is selected for editing:
$('#instance1 , #instance2').click(function () {
//Reposition the editor to just above the selected instance
$('#myNicPanel').css({
top: $(this).position().top,
left: $(this).position().left,
display: 'block',
width: $(this).width() - 2 //manual adjustment,
position: 'absolute'
});
//Make the width of the editor equal to that of the instance
$('#myNicPanel').css({
top: $(this).position().top - $('#myNicPanel').height()
});
});
You would of course already have initiated your editor and instances prior to this, and if you also want to have the editor hide again on blur, you could attach your hide() function to one of the nicEditor events.

Dropdownlist width in IE

In IE, the dropdown-list takes the same width as the dropbox (I hope I am making sense) whereas in Firefox the dropdown-list's width varies according to the content.
This basically means that I have to make sure that the dropbox is wide enough to display the longest selection possible. This makes my page look very ugly :(
Is there any workaround for this problem?
How can I use CSS to set different widths for dropbox and the dropdownlist?
Here's another jQuery based example. In contrary to all the other answers posted here, it takes all keyboard and mouse events into account, especially clicks:
if (!$.support.leadingWhitespace) { // if IE6/7/8
$('select.wide')
.bind('focus mouseover', function() { $(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'); });
}
Use it in combination with this piece of CSS:
select {
width: 150px; /* Or whatever width you want. */
}
select.expand {
width: auto;
}
All you need to do is to add the class wide to the dropdown element(s) in question.
<select class="wide">
...
</select>
Here is a jsfiddle example.
Creating your own drop down list is more of a pain than it's worth. You can use some JavaScript to make the IE drop down work.
It uses a bit of the YUI library and a special extension for fixing IE select boxes.
You will need to include the following and wrap your <select> elements in a <span class="select-box">
Put these before the body tag of your page:
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/yahoo_2.0.0-b3.js" type="text/javascript">
</script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/event_2.0.0-b3.js" type="text/javascript">
</script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/dom_2.0.2-b3.js" type="text/javascript">
</script>
<script src="ie-select-width-fix.js" type="text/javascript">
</script>
<script>
// for each select box you want to affect, apply this:
var s1 = new YAHOO.Hack.FixIESelectWidth( 's1' ); // s1 is the ID of the select box you want to affect
</script>
Post acceptance edit:
You can also do this without the YUI library and Hack control. All you really need to do is put an onmouseover="this.style.width='auto'" onmouseout="this.style.width='100px'" (or whatever you want) on the select element. The YUI control gives it that nice animation but it's not necessary. This task can also be accomplished with jquery and other libraries (although, I haven't found explicit documentation for this)
-- amendment to the edit:
IE has a problem with the onmouseout for select controls (it doesn't consider mouseover on options being a mouseover on the select). This makes using a mouseout very tricky. The first solution is the best I've found so far.
you could just try the following...
styleClass="someStyleWidth"
onmousedown="javascript:if(navigator.appName=='Microsoft Internet Explorer'){this.style.position='absolute';this.style.width='auto'}"
onblur="this.style.position='';this.style.width=''"
I tried and it works for me. Nothing else is required.
I used the following solution and it seems to work well in most situations.
<style>
select{width:100px}
</style>
<html>
<select onmousedown="if($.browser.msie){this.style.position='absolute';this.style.width='auto'}" onblur="this.style.position='';this.style.width=''">
<option>One</option>
<option>Two - A long option that gets cut off in IE</option>
</select>
</html>
Note: the $.browser.msie does require jquery.
#Thad you need to add a blur event handler as well
$(document).ready(function(){
$("#dropdown").mousedown(function(){
if($.browser.msie) {
$(this).css("width","auto");
}
});
$("#dropdown").change(function(){
if ($.browser.msie) {
$(this).css("width","175px");
}
});
$("#dropdown").blur(function(){
if ($.browser.msie) {
$(this).css("width","175px");
}
});
});
However, this will still expand the selectbox on click, instead of just the elements. (and it seems to fail in IE6, but works perfectly in Chrome and IE7)
There is no way to do it in IE6/IE7/IE8. The control is drawn by the app and IE simply doesn't draw it that way. Your best bet is to implement your own drop-down via simple HTML/CSS/JavaScript if it's that important to have the the drop-down one width and the list another width.
If you use jQuery then try out this IE select width plugin:
http://www.jainaewen.com/files/javascript/jquery/ie-select-style/
Applying this plugin makes the select box in Internet Explorer appear to work as it would work in Firefox, Opera etc by allowing the option elements to open at full width without loosing the look and style of the fixed width. It also adds support for padding and borders on the select box in Internet Explorer 6 and 7.
In jQuery this works fairly well. Assume the dropdown has id="dropdown".
$(document).ready(function(){
$("#dropdown").mousedown(function(){
if($.browser.msie) {
$(this).css("width","auto");
}
});
$("#dropdown").change(function(){
if ($.browser.msie) {
$(this).css("width","175px");
}
});
});
Here is the simplest solution.
Before I start, I must tell you dropdown select box will automatically expand in almost all the browsers except IE6. So, I would do a browser check (i.e., IE6) and write the following only to that browser. Here it goes. First check for the browser.
The code will magically expands the dropdown select box. The only problem with the solution is onmouseover the dropdown will be expanded to 420px, and because the overflow = hidden we are hiding the expanded dropdown size and showing it as 170px; so, the arrow at the right side of the ddl will be hidden and cannot be seen. but the select box will be expanded to 420px; which is what we really want. Just try the code below for yourself and use it if you like it.
.ctrDropDown
{
width:420px; <%--this is the actual width of the dropdown list--%>
}
.ctrDropDownClick
{
width:420px; <%-- this the width of the dropdown select box.--%>
}
<div style="width:170px; overflow:hidden;">
<asp:DropDownList runat="server" ID="ddlApplication" onmouseout = "this.className='ctrDropDown';" onmouseover ="this.className='ctrDropDownClick';" class="ctrDropDown" onBlur="this.className='ctrDropDown';" onMouseDown="this.className='ctrDropDownClick';" onChange="this.className='ctrDropDown';"></asp:DropDownList>
</div>
The above is the IE6 CSS. The common CSS for all other browsers should be as below.
.ctrDropDown
{
width:170px; <%--this is the actual width of the dropdown list--%>
}
.ctrDropDownClick
{
width:auto; <%-- this the width of the dropdown select box.--%>
}
if you want a simple dropdown &/or flyout menu with no transition effects just use CSS... you can force IE6 to support :hover on all element using an .htc file (css3hover?) with behavior (IE6 only property) defined in the conditionally attached CSS file.
check this out.. it's not perfect but it works and it's for IE only and doesn't affect FF. I used the regular javascript for onmousedown to establish IE only fix.. but the msie from jquery could be used as well in the onmousedown.. the main idea is the "onchange" and on blur to have the select box return to normal... decide you're own width for those. I needed 35%.
onmousedown="javascript:if(navigator.appName=='Microsoft Internet Explorer'){this.style.width='auto'}"
onchange="this.style.width='35%'"
onblur="this.style.width='35%'"
BalusC's answer above works great, but there is a small fix I would add if the content of your dropdown has a smaller width than what you define in your CSS select.expand, add this to the mouseover bind:
.bind('mouseover', function() { $(this).addClass('expand').removeClass('clicked');
if ($(this).width() < 300) // put your desired minwidth here
{
$(this).removeClass('expand');
}})
This is something l have done taking bits from other people's stuff.
$(document).ready(function () {
if (document.all) {
$('#<%=cboDisability.ClientID %>').mousedown(function () {
$('#<%=cboDisability.ClientID %>').css({ 'width': 'auto' });
});
$('#<%=cboDisability.ClientID %>').blur(function () {
$(this).css({ 'width': '208px' });
});
$('#<%=cboDisability.ClientID %>').change(function () {
$('#<%=cboDisability.ClientID %>').css({ 'width': '208px' });
});
$('#<%=cboEthnicity.ClientID %>').mousedown(function () {
$('#<%=cboEthnicity.ClientID %>').css({ 'width': 'auto' });
});
$('#<%=cboEthnicity.ClientID %>').blur(function () {
$(this).css({ 'width': '208px' });
});
$('#<%=cboEthnicity.ClientID %>').change(function () {
$('#<%=cboEthnicity.ClientID %>').css({ 'width': '208px' });
});
}
});
where cboEthnicity and cboDisability are dropdowns with option text wider than the width of the select itself.
As you can see, l have specified document.all as this only works in IE. Also, l encased the dropdowns within div elements like this:
<div id="dvEthnicity" style="width: 208px; overflow: hidden; position: relative; float: right;"><asp:DropDownList CssClass="select" ID="cboEthnicity" runat="server" DataTextField="description" DataValueField="id" Width="200px"></asp:DropDownList></div>
This takes care of the other elements moving out of place when your dropdown expands. The only downside here is that the menulist visual disappears when you are selecting but returns as soon as you have selected.
Hope this helps someone.
this is the best way to do this:
select:focus{
min-width:165px;
width:auto;
z-index:9999999999;
position:absolute;
}
it's exactly the same like BalusC solution.
Only this is easier. ;)
A full fledged jQuery plugin is available. It supports non-breaking layout and keyboard interactions, check out the demo page: http://powerkiki.github.com/ie_expand_select_width/
disclaimer: I coded that thing, patches welcome
http://developer.yahoo.com/yui/examples/button/button-menu-select.html#
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');
})
}
}
You can add a style directly to the select element:
<select name="foo" style="width: 200px">
So this select item will be 200 pixels wide.
Alternatively you can apply a class or id to the element and reference it in a stylesheet
So far there isn't one. Don't know about IE8 but it cannot be done in IE6 & IE7, unless you implement your own dropdown list functionality with javascript. There are examples how to do it on the web, though I don't see much benefit in duplicating existing functionality.
We have the same thing on an asp:dropdownlist:
In Firefox(3.0.5) the dropdown is the width of the longest item in the dropdown, which is like 600 pixels wide or something like that.
This seems to work with IE6 and doesn't appear to break others. The other nice thing is that it changes the menu automatically as soon as you change your drop down selection.
$(document).ready(function(){
$("#dropdown").mouseover(function(){
if($.browser.msie) {
$(this).css("width","auto");
}
});
$("#dropdown").change(function(){
if ($.browser.msie) {
$("#dropdown").trigger("mouseover");
}
});
});
The hedgerwow link (the YUI animation work-around) in the first best answer is broken, I guess the domain got expired. I copied the code before it got expired, so you can find it here (owner of code can let me know if I am breaching any copyrights by uploading it again)
http://ciitronian.com/blog/programming/yui-button-mimicking-native-select-dropdown-avoid-width-problem/
On the same blog post I wrote about making an exact same SELECT element like the normal one using YUI Button menu. Have a look and let me know if this helps!
Based on the solution posted by Sai, this is how to do it with jQuery.
$(document).ready(function() {
if ($.browser.msie) $('select.wide')
.bind('onmousedown', function() { $(this).css({position:'absolute',width:'auto'}); })
.bind('blur', function() { $(this).css({position:'static',width:''}); });
});
I thought I'd throw my hat in the ring. I make a SaaS application and I had a select menu embedded inside a table. This method worked, but it skewed everything in the table.
onmousedown="if(navigator.appName=='Microsoft Internet Explorer'){this.style.position='absolute';this.style.width='auto'}
onblur="if(navigator.appName=='Microsoft Internet Explorer'){this.style.position=''; this.style.width= '225px';}"
So what I did to make it all better was throw the select inside a z-indexed div.
<td valign="top" style="width:225px; overflow:hidden;">
<div style="position: absolute; z-index: 5;" onmousedown="var select = document.getElementById('select'); if(navigator.appName=='Microsoft Internet Explorer'){select.style.position='absolute';select.style.width='auto'}">
<select name="select_name" id="select" style="width: 225px;" onblur="if(navigator.appName=='Microsoft Internet Explorer'){this.style.position=''; this.style.width= '225px';}" onChange="reportFormValues('filter_<?=$job_id?>','form_values')">
<option value="0">All</option>
<!--More Options-->
</select>
</div>
</td>
I've had to work around this issue and once came up with a pretty complete and scalable solution working for IE6, 7 and 8 (and compatible with other browsers obviously).
I've written a whole article about it right here: http://www.edgeoftheworld.fr/wp/work/dealing-with-fixed-sized-dropdown-lists-in-internet-explorer
Thought I'd share this for people who are still running into this problem, as none of the above solutions work in every case (in my opinion).
I tried all of these solutions and none worked completely for me. This is what I came up with
$(document).ready(function () {
var clicknum = 0;
$('.dropdown').click(
function() {
clicknum++;
if (clicknum == 2) {
clicknum = 0;
$(this).css('position', '');
$(this).css('width', '');
}
}).blur(
function() {
$(this).css('position', '');
$(this).css('width', '');
clicknum = 0;
}).focus(
function() {
$(this).css('position', 'relative');
$(this).css('width', 'auto');
}).mousedown(
function() {
$(this).css('position', 'relative');
$(this).css('width', 'auto');
});
})(jQuery);
Be sure to add a dropdown class to each dropdown in your html
The trick here is using the specialized click function (I found it here Fire event each time a DropDownList item is selected with jQuery). Many of the other solutions on here use the event handler change, which works well but won't trigger if the user selects the same option as was previously selected.
Like many of the other solutions, focus and mousedown is for when the user puts the dropdown in focus, blur is for when they click away.
You may also want to stick some kind of browser detection in this so it only effects ie. It doesn't look bad in other browsers though
Its tested in all version of IE, Chrome, FF & Safari
JavaScript code:
<!-- begin hiding
function expandSELECT(sel) {
sel.style.width = '';
}
function contractSELECT(sel) {
sel.style.width = '100px';
}
// end hiding -->
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>

Categories