jQuery Modal Dialog : Hide That Stupid X Button / Windows Close Button
This is quick one, so hold on to your... whatever.
Want to get rid of that X at the top right of the modal "Control"? Well here it is: (The bold part, moron)
jQuery('#WaitingDiv').dialog({ autoOpen: false, bgiframe: false, height: 150, width: 200, modal: true, open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });
And that's really it. Just thought I'd pass that on to you, the consumer.
On a side note, the big movie thing is the canceling of Spiderman 4 or at least going in a new direction. As much as I don't care, it might lead to my dream come true:
A spiderman movie based on the SNES classic: Spider-Man & Venom: Maximum Carnage. Uwe Boll, are you out there?
jQuery – Check All Checkboxes Toggle Method Thingy
So here's a quick on for all you boys and girls... and anything else I might have missed.
Say you want to check all check boxes in a grid or whatever, but you want it to toggle. So if if it's time to check all, all get checked and then the next time the button is clicked it will uncheck. Now you could do this in three methods, maybe two but that's why you're a mouth breather.
Special people like me do it in one.
function toggleCheckboxes(buttonId, checkBoxNamePrefix, checked) { //Get all checkboxes with the prefix name and check/uncheck jQuery('[id*=' + checkBoxNamePrefix + ']').attr('checked', checked); //remove any click handlers from the button // Why? Because jQuery(buttonId).click() will just add another handler jQuery(buttonId).unbind('click'); //Add the new click handler jQuery(buttonId).click( function() { toggleCheckboxes(buttonId, checkBoxNamePrefix, !checked); } ); }
And POW! What? You want to know how to use it? Fine, but only because I'm nice.
jQuery('#buttonName').click( function() { toggleCheckboxes('#buttonName', 'someCheckBoxName', true); } );
And in case you were still wondering why I used .unbind and didn't understand the comment, it's because using just .click will add another handler to the button. So next click you will get both check and uncheck all. Kind of hurts the effectiveness.
And there you have it. Once again I have filled your life with meaning. Couldn't be easier. Or maybe it could but that's not my problem now is it? Go back to doing something useful.
jQuery Grab Bag – Whole bunch of jQuery Functionality
You could look at this post as a self serving block that I will use to save stuff I don't want to remember later.
Or you could see it as a knowledge transfer that you the reader can learn from because I am a generous and giving tool.
Whatever, I really don't care. I won't sleep any differently. I just don't feel like making 1000 posts of jquery stupidity.
I'll add more as I come across them.
Checkbox
How To Check a CheckBox
jQuery('#CheckBoxId').attr('checked', false);
How To Know if a Checkbox is Checked
jQuery('#CheckBoxId').is(':checked')
How To Find a Bunch of Like Named Checkboxes that are Checked
jQuery('[id*=someCheckBox_]:checked');
Drop Down Lists
How to Add an Item/Option to a Drop Down List
jQuery('#DropDownListId').append(jQuery('<option>').val(1).html("SomeText"));
Odd Note: Apparently jquery is smart enough to set the attributes on the option AND close the option with </option>
How to Remove an Item/Option from a Drop Down List
jQuery('#DropDownListId option[value=\'3\']').remove();
How to Sort a Drop Down List by Option Text
var sortedList = jQuery('#someDropDownList option').sort( function (first, second) { return first.text == second.text ? 0 : first.text < second.text ? -1 : 1; } ); jQuery('#someDropDownList').html(sortedList);
Elements
How to Filter Out an Element in a List
someElementList.filter('[id=someId]');
Example:
//Uncheck all id like someId_ and check only where id = someId_1 var someElementList = someElement.children('[id*=someId_]'); someElementList.attr('checked', false); someElementList.filter('[id=someId_1]').attr('checked', true);
How To Find an Element Based on a Like Name/Using Wildcards
jQuery('#SomeTable').children('tr[id*=SomeRowId]');
How To Know if a Something is Hidden
jQuery('#CheckBoxId').is(':hidden')
Possible Use:
function showOrHide(element) { if(jQuery(element).is(':hidden')) { jQuery(element).show(); } else { jQuery(element).hide(); } }
How to Disable an Input/Select
jQuery('#DropDownListId').attr('disabled', 'disabled');
How to Enable an Input/Select
jQuery('#DropDownListId').removeAttr('disabled');
How to Know if an Element Exists
jQuery('#ElementId').length > 0
Possible use:
function elementExists(elementId) { return jQuery(elementId).length > 0; }
String
How To Remove the First Character from a String
someString.substring(1, someString.length)
Tables
How to Add a Row to a Table
jQuery('#TableId > tbody:last').append('<tr>...</tr>')
How to Remove a Table Row
jQuery('#TableId > tbody:last').children(someSortOfRowId).remove();
Methods
How to Post With a Link
function postToUrl(path, params) { var method = "post"; var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); for(var key in params) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } document.body.appendChild(form); form.submit(); }
Use:
<a href="javascript:postToUrl('/SomeController/SomeAction/', { 'id', '1' })">link</a>
jQuery: Find All Checked Checkboxes
So this is sort of a repeat of another post, but I figured it has some use on its own.
Say you have this:
<div> <input type="checkbox" name="JqueryIdList" value="1" /> <input type="checkbox" name="JqueryIdList" value="2" /> <input type="checkbox" name="JqueryIdList" value="3" /> <input type="checkbox" name="JqueryIdList" value="4" /> </div> <div onclick="getIds('JqueryIdList');"> CLICK </div>
And you need the getIds method to find all the checked checkboxes from that markup. Well it's actually fairly simple, or at least it wil be once I enlighten you. I should get paid for this...
function getIds(checkList) { var idList = new Array(); var loopCounter = 0; //find all the checked checkboxes jQuery("input[name=" + checkList + "]:checked").each ( function() { //fill the array with the values idList[loopCounter] = jQuery(this).val(); loopCounter += 1; } ); ... }
The important part is this:
jQuery("input[name=" + checkList + "]:checked").
As you can see, it is very simple. Give it the name of the checkboxes, add on the ":checked" and boom you have a list of checked checkboxes. Could it be more simple? I think not.
jQuery: Holy Smokes I Like This Link
Good old Stackoverflow. Wasn't sure how to post this without looking like I'm trying to get search engine hits. However, wanted to pass this one on anyhow.
How to center a div using jQuery.
Have used it. Works brilliantly. Although the:
this.css("position","absolute");
May be overkill since any "pop up" div I create already has that in the style where personally I think it should be.
How does it work? Well break down the "top" part:
this.css("top", ( jQuery(window).height() - this.height() ) / 2+jQuery(window).scrollTop() + "px");
To
jQuery(window).height() - this.height() ) / 2
But why not just divide the height by 2? Well say the height of the window is 800 and your item is 600 high. If you just placed the item at 800 / 2, the bottom of the item would end up 1000. (800/2 = 400... 600 tall item + 400 starting point = 1000). So subtracting the item's height from the window height and THEN dividing by two ensures that that item, provided it is no taller than the window, will end up within the 800 tall window.
+ jQuery(window).scrollTop()
Now what if the user has scrolled the widow down? Well adjust for that. using the scrollTop(), the item can be started at the correct point adjusted with the scroll. Nice huh?
Javascript: Scope and Learning Something New Everyday.
Course for me it doesn't take much to learn something new, but let's not get into that.
So pop quiz, and one that doesn't involve a hostage and shooting.
jQuery(document).ready ( function() { for(var loopCounter = 0; loopCounter < 3; loopCounter++) { var tempThing = loopCounter; alert('in' + tempThing); jQuery(".someButton").click ( function() { alert('out' + tempThing); } ); } } ); .... <button class="someButton">click!</button>
What happens when you click that button? Well for one it will alert three times but what will it print out?
The first alert (in the loop) does what you would expect. It gives 0, 1, 2. But what about the button click? Well that's a little different. It gives 2, 2, 2... Wait what? The f--- is that? That makes no real sense.
Given that this was C#, it would output 0, 1, 2 because we would know that every loop the tempThing field is a new field. Sure it has the same name in code, but every iteration would create a new space in memory for a new tempThing. And then with closures, a reference would be made to that tempThing so that when the method actually runs, the values are what they should be. Javascript does something a little different. Go figure, right? Can't do anything like anyone else... anyone else being C#.
Now what does happen is it does give you the correct value of tempThing. What you didn't know (Assuming you didn't know because if you are reading this you either are really bored or don't know... or both) is that tempThing is global to that method. Turns out variables are global to the current scope no matter if in a loop or not. tempThing, no matter where in that function is created/instantiated/ect is the same tempThing through out the method. So what's happening is that the first time in the loop it's being created and every iteration after it's just being updated with the current loopCounter value.
How do you solve this? Well you have to make a method to create a method to set the value. AWESOME!!111
jQuery(document).ready ( function() { for(var loopCounter = 0; loopCounter < 3; loopCounter++) { alert('in' + tempThing); jQuery(".someButton").click ( createReturnMethod(loopCounter) ); } } ); //This is used to create a new method scope so that //tempThing is unique to each call. function createReturnMethod(loopCounter) { var tempThing = loopCounter; return function(event) { alert('out' + tempThing); }; }
As you can see, I created a method to create a method to be run on click. Because tempThing is now in the second method's scope, it will be different for every time this method is called. Magic!
Here's a thought, if only you can prevent forest fires then you really should get on that. People have lost a lot of money because of your slacking.
jQuery Whack-A-Mole… Timer, Hide, Slide, and Fun
So I'll just straight up file this under "I really shouldn't have" and not bother asking for forgiveness. For some reason I had it in my mind I wanted to see if I could take the stuff I learned from this guy and this guy and see if I could make a simple Whack A Mole game with just jquery and the three include files. (jquery, jquery UI, and jquery Timer) Not thinking of the massive consequences such a thing might bring, I pushed on in the name of science.
So with no further build up or stupidity (I used that all up in building this game) I give you jQuery WHACK A MOLE which oddly enough has somehow clawed it's way into my hosting here. So if you're foolish enough to actually want to know how it works, there are plenty of comments in the script files. Just don't blame me for any loss of intelligence.
I might actually take this to the next horrifying level and make it an mvc application. Not sure I... no... THE WORLD can take it.
jQuery: Slide Menu With Pop Up Divs. Yay!
So you may have seen this post about how I came to create such a wonderful menu with no real purpose as of yet. Well that menu has been improved and can be downloaded here.
Remember that question you never asked? Well once again I've answered it.
To take the normal sliding menu farther I thought I should have something happen when hovering over the menu items. Novel! Well as you can see if you clicked on the link above (Sorry, can't repost the link. Links are expensive.) the menu items have large counter parts that show up when hovered over and don't go away until the counter part or the main item is left. What does this all mean? I DON'T KNOW but I'll find out eventually. It's in the cards man, it's in the cards...
Ok so additions... For the style sheet, I added a class:
.menuItemBig { height:100px; margin-right:5px; position:absolute; width:100px; z-index:100; }
And have included a child div to the menu item:
Before
<div class="menuItem floatLeft blue">1</div>
Now
<div class="menuItem floatLeft blue"> 1 <div class="menuItemBig red">THIS IS THE BIG ITEM 1</div> </div>
I added two methods:
// // mouseenter: Find any menuItemBig within the given element and show // Reset the position of the menuItemBig element to appear // to be in the middle of the parent element // mouseleave: Hide the child menuItemBig // function setOnHoverForMenuItems(items) { jQuery(items) .each ( function () { jQuery(this).mouseenter ( function() { //Why the positioning? I wanted the child div to show up in the // middle of the parent div which is done by putting the child's left side // to half of the width of the parent over from the parent's left side var parentPosition = jQuery(this).position(); var bigItems = jQuery(this).children(".menuItemBig"); bigItems.css({ left: parentPosition.left - (jQuery(this).width() /2), top: parentPosition.top + 10 }); bigItems.show(); } ); jQuery(this).mouseleave ( function() { jQuery(this).children(".menuItemBig").hide(); } ); } ); }
Why not hover? *EDIT* It should be hover. Turns out an issue I was having with hover was not actually an issue with it... *END EDIT*
The other method I added was a simple one:
// // Used to find any element of menuItemBig // function hideAllBigItems(bigItemParentItems) { jQuery(bigItemParentItems).children(".menuItemBig").hide(); }
And where did I use these? I appended them to the setChildrenDivs method:
function setChildrenDivs(mainHolder) { var menuItems = getMenuItems(mainHolder); for (var loopCounter = 0; loopCounter < menuItems.length; loopCounter++) { if(loopCounter > maximumToShow - 1) { jQuery(menuItems[loopCounter]).hide(); } } setPager(jQuery(mainHolder).children(".leftPager"), getLastVisible, getNextInLineBack); setPager(jQuery(mainHolder).children(".rightPager"),getFirstVisible, getNextInLineFront); setOnHoverForMenuItems(menuItems); hideAllBigItems(menuItems); }
So in all, this didn't take much at all, thanks to mouseleave. Next up... not sure. No idea if I will take this any further.
jQuery Slide and Pairing a Div’s Hover With a Div’s Slide
So this could be filed under "I did it because I can" (which is a really good mantra in science...) and am not sure I'll use it but it is useful in the concept.
The idea is to set the hover on one div to show/hide another div WITHOUT having to use some kind of id/name trick (as in setting the id to "divHide1") and to have it be completely self setting in the .ready method. Why would this be at all useful? Say you want to roll through a list of things and generate the divs, but want to defer the jQuery until the page has loaded. And you don't want to have to resort to:
<div id="someDiv<%= someId %>"></div>
like structure where you parse some identifier from the id property. Mostly because you have no idea how many someDiv1s there could be on the page. It could be a highly reused name (someDiv) and that could lead to a mess.
Also the reason 'cuz. If you have any more questions of why after that answer, well you're just being annoying.
Anywho, here's the actual html for structure.
<div class="mainDiv"> <div class="showDiv" id="oneTop"> Kaneda? </div> <div class="slideDiv" id="one"> What do you see?! </div> </div> <div class="clear"></div>
Now I get that this isn't off a foreach, but it doesn't take much to figure out that it's easily made into a loop if you just loop it over and over. Why? Because first there are no ids or names so that you can't have two of the same name and also because that chunk is self contained.
So what is going on there? Simple, you have a parent container that holds a div to hold and a div to hover over and the other that will be shown/hidden.
Here's the styles involved just incase you care:
<style type="text/css"> .clear { clear:both; } .leftDiv { float:left; } .mainDiv { margin:5px; height:200px; } .rightDiv { float:left; } .showDiv { float:left; margin-right:5px; height:200px; background-color:Silver; } .slideDiv { background-color:Teal; height:200px; position:absolute; float:left; z-index:100; } </style>
That doesn't entirely matter, but it does to show the div "sliding" over another div. Kind of a little somethin' somethin' I threw in at no extra cost. Now for the jQuery:
First the method for setting the mouse over and out events for the show div, we turn to .hover:
function setHover(currentSlideDiv, currentStableDiv) { currentStableDiv.hover ( //first parameter is the method for showing the div on mouse over function() { if (currentSlideDiv.is(":hidden")) { currentSlideDiv.show("slide", { direction: "left" }, 100); } }, //second parameter is the method for hiding the div on mouse out function() { if (currentSlideDiv.is(":visible")) { currentSlideDiv.hide("slide", { direction: "left" }, 100); } } ); };
Now for the method that actually uses these:
//This is used to take in one of the main divs and set all the //show and slide divs within. function setChildrenDivs(mainDiv) { //get all the show and slide dvis within the main div var mainChildrenStableDiv = jQuery(mainDiv).children(".showDiv"); var mainChildrenSlide = jQuery(mainDiv).children(".slideDiv"); //loop through the list of show divs for (var loopCounter = 0; loopCounter < mainChildrenStableDiv.length; loopCounter++) { //Get the show div and it's corresponding slide div using the //two lists and the current counter. var currentStableDiv = jQuery(mainChildrenStableDiv[loopCounter]); var currentSlideDiv = jQuery(mainChildrenSlide[loopCounter]); //This is to make sure the slide is where it should be. //to the right of the show div. var containerPosition = jQuery(currentStableDiv).position(); jQuery(currentSlideDiv).css({ left: containerPosition.left + currentStableDiv.width() }); //Set the mouse over and the mouse out on the show div setHover(currentSlideDiv, currentStableDiv); } }
Now the final touch, the .ready method:
jQuery(document).ready
(
function()
{
//hide all the slide divs
jQuery(".slideDiv").hide();
//find all the parent divs
var mainDivs = jQuery(".mainDiv");
//set the children
for (var loopCounter = 0; loopCounter < mainDivs.length; loopCounter++)
{
setChildrenDivs(mainDivs[loopCounter]);
}
}
);
And boom, now you have multiple show/hide (Slide in this instance). Now if I could just find a use for it...
Oh yeah and you'll need jQuery 1.3.2 and jQuery ui 1.7.2 to use this. At least those are the versions I know this works with.
Update: Due to popular demand... one person... Source can be found here.

