Stop the IPhone / Safari from Minimzing a Page

Real quick one, but I thought this was crazy useful.

If you’re developing a web based app that might be used by IPhone users, there is a simple way to stop the IPhone from shrinking the page onload. Thanks to Mark W on The Stack Hath Runith Over there is a simple solution.

  <head runat="server">
     <title>I LOVE TITLES!</title>
     <meta name="viewport" content="width=420" />

That one beautiful metatag makes life worth living again… until the next Street Fighter movie comes out. Then life is back in the forfeit container. Here’s a link to more options:
BYEBYE

jQuery: Add a Pop Up Div to a Link Dynamically

So as an exercise to learn more about jQuery, I decided to redo this little gem using jQuery. Have to say though only technically XHTML compliant, it worked out much better and with less code. So the idea is to have something really easy for non programmers (You know, lesser people) to be able to have a pop up comment added to some chunk of text on a web site. What I came up with before was ok but kind of annoying since it looked like this:

<a onclick="return ShowCommentForPost('1', this, 'THIS IS SO STUPID!');" href="www.byatool.com">word.</a>

Kind of annoying since I would have to explain that ‘1’ is the name and it has to be unique for every one of these, this isn’t really understood by those people, and well it just seems more complicated then it needs to be. So what if I told you it could look like this?

<a href="http://www.byatool.com" class="showItLink" xmlns:comment="hihihi">HI</a>

Gorsh, that seems even better and it works in both IE and Firefox… which might be a first for this site and anything javascript. First let’s get the css out of the way, shall we?

    .showItLink
    {
    }

    .postComment
    {
        background-color:Gray;
        border-color:Black;
        border-style:dotted;
        border-width:thin;
        color:White;
        margin-right:3px;
        padding:3px;
        position:absolute;
        text-decoration:none;
        z-index:50;
    }

Most of the is just for looks, but like the older example I’ve called upon the power of position:absolute and z-index well that’s just pulling it in front of everything else.

Next part will be the actual code, and if you take the method from THE POSITION ABSOLUTE POST

    function SetTopAndLeft(parentContainer, elementToSet)
    {
        var containerPosition;

        containerPosition = $(parentContainer).position();
        $(elementToSet).css({ top: containerPosition.top + 10, left: containerPosition.left + 10 });
    }

and add in a simple span creation method:

    function CreateDiv(innerText, cssClass)
    {
        var spanToAdd;

        spanToAdd = document.createElement('span');
        spanToAdd.className = cssClass;
        spanToAdd.innerHTML = innerText;

        return spanToAdd;
    }

you’re ready for the actual fun part… making sure something pops up when the link is clicked.

jQuery(document).ready  //Everything inside this will load as soon as the DOM is loaded and before the page contents are loaded.*
(
    function()  //this is the start of an anonymous method
    {
        jQuery(".showItLink").click //find all things with the .showItLink class and assign the click event to the next anonymous method
        (
            function(event) //this is the start of an anonymous method for the click event
            {
                var containerPosition;
                var createdSpan;
                var comment;

                comment = jQuery(this).attr("xmlns:comment");  //Get the value from the comment attribute on the link.
                createdSpan = jQuery(this).children(".postComment"); //Find a possible span already attached to the link if it exists.  The span is of class 'postComment'

                if (createdSpan.length == 0)  //span doesn't exist
                {
                    createdSpan= CreateDiv(comment, "postComment");  //create the span
                    jQuery(this).append(createdSpan);  //Add the span to the link
                    jQuery(this).children(".postComment").hide();  //Make sure the new span is hidden
                }
                SetTopAndLeft(this, createdSpan);  //Set the position of the span
                jQuery(createdDiv).toggle();  //This will hide if it's showing, show if it's hidden... kind of nice huh?

                event.preventDefault();  //Equivalent to false.  Need this for Firefox.
            }
        );
    }
);

And boom you have something that works. Hooray.

Couple things of note:

.Hide – At first I though this would screw up my class for the span by removing the current class and adding display:none. Turns out it doesn’t harm the original class. Kind of nice.

.Toggle() – This is really nice. It will hide if it is showing and show if hidden. Stupid easy to use and is pretty effective. Just like .Hide, the class of the element is not harmed.

$ versus jQuery – Some people might notice that I am not using the short hand $ for my jQuery calls. Turns out that it might be safer this way. There are other javascript libraries that use the $ short hand like prototype. I ran into this with WordPress since it uses both jQuery and Prototype and blocks jQuery from using $ since it could conflict with other libraries. Weeeee!

JQuery, Position : Absolute, and How to Make It All Work

This is a really quick one but when I was taking my cheesy pop up and reworking it using JQuery (After Andre the Annoying wouldn’t shut up about it), I ran into a fun problem: position:absolute wasn’t working like it should. You know “absolute is positioned at the specified coordinates relative to its containing block.”. Meaning it should at worst show up within it’s container, where ever that is. Now IE is fine with that and the thing was showing up well:

absolutepositionie

Firefox? Not so much:

absolutepositionfirefox

Well… turns out JQuery pretty much does it for me. With a simple method, you can set one element’s position relative to a parent’s position:

    function SetTopAndLeft(parentContainer, elementToSet)
    {
        var containerPosition;

        containerPosition = $(parentContainer).position();
        $(elementToSet).css({ top: containerPosition.top + 10, left: containerPosition.left + 10 });
    }

Really simple, you get the position of the parent container and you set the child element’s top and left to it. Or in this case, I have it just off since hiding the parent container could be problematic. (Say if the parent container is a link AND NOW YOU CAN’T FIND IT TO CLICK ON IT AND THINGS HAPPEN BAD THINGS AND THE WORLD EXPLODES BECAUSE OF YOU!)

And boom, you can for once be a winner just like me.

Add a Pop Up Div to a Link Dynamically

Sometimes in life you have to ask “should I do this”, this is not one of those times. The idea is simple, click on a link and a div appears over the link with some kind of message in it. Kind of like being able to add a pop up note to a word. If you are absolutely amazed by that, don’t be afraid. Most likely you’ll die soon from forgetting to breathe. However, if you are just slightly curious as to why and how, keep reading.

So why did I do this? Well it started with the idea of having something simple for a blog that has multiple authors: What if other authors could add notes to someone’s post in the post. Well the idea of using some kind of text change (Like italics) sounded lame. I wanted something easy that could be replicated quickly and wouldn’t be visible unless needed. Thus the onClick idea. Now the next problem I had was the class needed for the style sheet. As you can see, when the div is shown, it doesn’t displace any of the items on the page. This is because I am using position:absolute and a high z-index. This allows for the div to lay on top of other things and not touch them. Problem with absolute is that it basicaly plants the div in relation to it’s parent container. Now that whole parent container thing seems to be up for interpretation when you are talking about browsers. Each seems to deal with it the way it sees fit.

Originally I had it as a div that would contain this new div. This was a pain in the -ss. In IE it showed up over the div, FireFox not so much. So the next thought was to create a div to hold the div that held the div. Something that isn’t exactly “user friendly” to be sure. Then it hit me, maybe I could put this in a link. After all, people who are viewing the blog would understand it’s something they can click on (Provided I don’t screw with the link styles too much) and it’s easy for non coders to copy and paste.

So on to the promised land. First I’ll just get the CSS out of the way since it’s absolutely needed but needs little explanation:

.hidePostComment
{
    visibility:hidden;
    position: absolute;
    z-index:-100;
}

.showPostComment
{
    background-color:Gray;
    border-color:Black;
    border-style:dotted;
    border-width:thin;
    color:White;
    margin-right:3px;
    padding:3px;
    position:absolute;
    text-decoration:none;
    visibility:visible;
    width:100px;
    z-index:10;
}

.hidePostComment

As you can see, I’ve screwed with the z-index, visibility, and position. Position I’ve already explained, and I think you can understand why visibility is hidden with this class. However, z-index might not be something you know about. Basically,z-index tells the browser where an item is in a vertical sense. When you look at a browser, there are actually a lot of layers regardless of the 2nd appearance. The z-index is used to bring something forward or backward. If I want the div to be behind say the text I am typing right now, it has to be at a z-index lower than the text. I used -100 in the example just to make sure it’s behind anything. It’s really an arbitrary number though. A positive number would make the div appear in front of the text (And in that case the text would not show up since it would be “behind” the div) which is what I did with the visibility class.

.showPostComment

Mostly just a bunch of visual changes like border and background color. However, you will also notice the the position is still absolute and that the z-index is now 10. (positive) The div will now effectively be “in front” of the link when it shows up giving it the pop up look. One Note: I had to add in text-decoration:none since the div is attached to the link and IE wants to drag the underline with the pop up causing the text to up with an underline. Kind of odd but no big deal.

Now for the code:

function BuildSelectableSpanForPost(spanName, parentElement, innerText)
{
    var divToAdd;
    var parentContainer;
    //check to see if the parentElement is actually an element or string.  If string, use it
    //to find the element.
    if (typeof parentElement == 'string')
    {
        parentContainer = document.getElementById(parentElement);
    }
    else
    {
        parentContainer = parentElement;
    }
    //Create the div
    //set the name (The name must unique since there could be a million "pop ups" per page
    //set the id
    //set the text for the div which is what we want to show up in the pop up
    divToAdd = document.createElement('span');
    divToAdd.setAttribute('name', spanName);
    divToAdd.id = spanName;
    divToAdd.innerHTML = innerText;

    //Add the div to whatever element that was found.  For this post it will be a link
    //but it doesn't really matter.
    parentContainer.appendChild(divToAdd);

    return divToAdd;
}

So there is the building of the pop up div. Here’s the method to be called by the onclick event:

function ShowCommentForPost(postName, parentElement, innerText)
{
    var divName;
    var createdDiv;
    var parentContainer;

    //Same as before
    if (typeof parentElement == 'string')
    {
        parentContainer = document.getElementById(parentElement);
    }
    else
    {
        parentContainer = parentElement;
    }
    //See if the pop up div  already exists.  If it does, then don't create again
    //I didn't have this before and it would create a new div everytime
    //That's what some might call a surprise feature
    divName = 'comment' + postName;
    createdDiv = document.getElementById(divName);
    //Ooops, the div didn't exist, create it and add the hide class
    if (createdDiv == null)
    {
        createdDiv = BuildSelectableSpanForPost(divName, parentContainer, innerText);
        //this is a method found on this post
        ClassHandler.AddClass(createdDiv, 'hidePostComment');
    }

    //this is a method based off this post
    //As you can guess it will show or hide depending on which class it already has.
    ShowHideElementBasedOnCss(createdDiv);

    return false;
}

To start, there is the code to create the actual div.

Now for the actual use:

<a onclick="return ShowCommentForPost('1', this, 'THIS IS SO STUPID!');" href="www.byatool.com">word.</a>

Pretty easy to actually use right? The actual location doesn’t really matter since it the method will always return false and therefore the link will never redirect. Also, you’ll see that I put 1 as the name sent in. The name sent in doesn’t matter what it is, but for every link it has to be different. If you are using this in a blog situation where there could be multiple blog posts in one page, I would suggest the name sent in would be the title and an increasing number.

If you got to this point and feel robbed of five minutes in your life, well just be happy this post robbed me of 15 minutes of mine.

Add, Remove, or Replace a CSS Class Using Javascript

Now honestly, I think the all famous Prototype has something for this, but if you aren’t using the all famous Prototype… well you’re screwed. Until now.

This is the idea, you want show or hide something on a click of it.

    <div onclick="HideOrShowMe();">
      YAYAAYAYAY!
    </div>

Annoying thing is trying to keep up with whether it’s hidden or not. Now there are ways to do this for sure, but if you had them you wouldn’t be here… or you just love idiotic banter. Either way, you’re here.

To start, get a class going:

    if (typeof ClassHandler != 'object')
    {
      ClassHandler = new Object();
    }

Normal declaration. Yeehaw. Now we need a method to check for the class:

ClassHandler.CheckForClass = function(element, nameOfClass)
{
    var returnValue = false;

    //Check to see if the element variable is a string or (hopefully) a control.
    //If it is a string, get the control that belongs to that id.
    if (typeof element == 'string')
    {
        element = document.getElementById(element);
    }

    //next you use a regular expression to check the className property for
    //  the class you want.  If it finds a match, you're good to go.
    if (element.className != '')
    {
        returnValue = new RegExp('\\b' + nameOfClass + '\\b').test(element.className);
    }

    return returnValue;
}

Ok so now you have a method to check if it’s there… but what about if you want to replace the old one with a new one? Well that could be broken into two methods first (Both that are useful). First one is the removal of the old class:

ClassHandler.RemoveClass = function(element, nameOfClass)
{
    var returnValue = false;

    //You know the drill
    if (typeof element == 'string')
    {
        element = document.getElementById(element);
    }

    //Hey cool, I just used the CheckForClass method
    if (ClassHandler.CheckForClass(element, nameOfClass))
    {
        //Real simple, replace the old
        //But you have to check if the nameOfClass exists with a preceding space
        //If it does, then you replace that with a space, other wise just replace
        //the nameOfClass with a space.
        element.className = element.className.replace((element.className.indexOf(' ' + nameOfClass) >= 0 ? ' ' + nameOfClass : nameOfClass),'');
        returnValue = true;
    } 

    return returnValue;
}

And now you’ll have to add in the new one.

ClassHandler.AddClass = function(element, nameOfClass)
{
    var returnValue = false;
    //lalalala
    if (typeof element == 'string')
    {
        element = document.getElementById(element);
    }
    //If className already has a value, precede the nameOfClass with a space
    // otherwise just add it in.
    if (!ClassHandler.CheckForClass(element, nameOfClass))
    {
        element.className += (element.className ?  '  '  :  '') + nameOfClass;
        returnValue = true;
    } 

    return returnValue;
}

Now for the replace:

ClassHandler.ReplaceClass = function(element, classToRemove, classToAdd)
{
    var returnValue = false;

    //african elephants only have four teeth for chewing their food.
    if (typeof element == 'string')
    {
        element = document.getElementById(element);
    }

    //Remove the old one
    //Add the new one
    if(ClassHandler.CheckForClass(element, classToRemove))
    {
        ClassHandler.RemoveClass(element, classToRemove);
        ClassHandler.AddClass(element, classToAdd);
        returnValue = true;
    }

    return returnValue;
}

Now you might be thinking, “Tool, why don’t you just use the replace method in the replace method.” Well I suppose you could, but this way you have two other methods at your disposal for future use. Up to you really, part of this was because I actually needed those methods and the title says “Add, Remove, or Replace”. I can’t go against the title. I don’t have that kind of strength.

Usage? Well there are couple ways you can do this.

    if(ClassHandler.CheckForClass('someDiv', 'hide'))
    {
       ClassHandler.ReplaceClass('someDiv', 'hide', 'show');
    }
    else
    {
       ClassHandler.ReplaceClass('someDiv', 'show', 'hide');
    }

or this:

    if(!ClassHandler.ReplaceClass('someDiv', 'hide', 'show'))
    {
       ClassHandler.ReplaceClass('someDiv', 'show', 'hide'));
    }

And other ways to be sure. Now I’m not saying this is the best way to do it, just a decent way… although looking back on this I wonder if I could clean up the regex stuff.

WordPress Plugin: Featured Content Gallery

Ok so this and a couple other sites I have are based off the WordPress blog things, and the original idea was just to get something out there and build things later. Turns out WordPress is actually quite impressive due to the large community of programmers. Now, I have to assume that there will be people out there that have blogs like this one (Except with less bleh and more yay) and might want to find ways to make them look better. So since I am constantly doing so, I thought I would start posting things I’ve found useful.

First one up is the Featured Content Gallery. Basically the idea is to be able to have a eh… Oh hell. I have no real way to describe it. Say you have featured stories/blogs posts that you want to show in a more extravagant way. Now say you have 4 of them and you want a rotating picture control that had a picture for each one. Now say you wanted it to look something like this: (And yes I stole this picture from the WordPress site)

Now you look at that and think, “Yeah right. That good?” Fact is, yeah. Now I could say it took me thirty minutes to set it up but that’s only because I didn’t read the instructions they had at the instruction page. Had I done that, it would have taken about five. The actual control itself is easy to put on a page. It basically takes one line:

<?php include (ABSPATH . '/wp-content/plugins/featured-content-gallery/gallery.php'); ?>

The setup is slightly harder (Or really hard if you’re confused by the phrase “Push button to start”) than copy and pasting things.

setupfeaturedplugin

Huh, looks real hard right? I mean you got this width and height thing. And oh wow, whether to choose a category or individual posts. Huh. (Although short note and once again proof that I need to read: I had difficulty at first figuring out that the “Post or Page IDs” section meant that I would have to put the PAGE ID of the POST in the TEXTBOX. Sometimes I really live up to my tool status)

Then the next tricky thing is getting the image to work. Oh and this is real hard…

setupfeaturedplugin2

Now you might or might know this is the Add/Edit post page. If you’ve never used the Custom Tag section, this also might be odd to you. And honestly, this was the first time I ever used it. Turns out you can set certain values to stick with each post and can be used programmatically like say Attributes on properties in c#. Now, see that part where I added a custom tag (“articleimg”) and gave it a url to an image? Yeah that’s the image that will be shown for that particular post. Now you may think this is kind of annoying that you have to do this for every post you want to feature, but you might also be the kind of person who complains it’s too much work to wash your dishes to avoid health problems.

There are other options too. You can set a special text for each featured item (As the default uses the post’s title) and you can set a thumbnail image instead of the cropped default it uses. And there are certain style values you can set in the maintenance page. However, I didn’t get a chance to use those yet.

Example you ask? Chance for me to plug a site you say? Well this plugin actually was used at The Ironical which is a side project I’m working on. Again, it’s a site I was just going to use WordPress for as a temporary thing but have been so impressed with all the customization, I’ve thought of relearning php… and then shortly after drinking a gallon of drano. My world is turning upside down.

Here’s my working example:

setupfeaturedplugin3

Cry on Favre. This plugin has brought me to happy tears too.