Pages

There are a couple of non-Javascript tricks at our disposal for hiding and showing content based on CSS. To be more precise, it is the use of pseudo-class selectors which can select for an element in a specific state.

We will cover two such states that we can utilize to show or hide content.

The first one is the :focus state. Here is a quick demo before we dive in to the explanation.

The :focus pseudo-class allows us to detect if an input has been “clicked” or not. “clicked” is in quotes because we are actually detecting if an input element is in focus. The main way for an element to be in focus is for a user to click on it so we are using focus as a proxy for a user clicking on an element. It’s mainly up to the browser on which elements can receive the focus event but the input text box is a safe choice which has good browser support.

Here is the HTML for the demo:

<input type="text" value="CLICK TO SHOW CONTENT">

<div id="content">

and the content will show.

</div>

The HTML is pretty simple with a text input and a div containing our content that we want to hide/show.

The CSS is where it gets interesting:

#content{

display:none;

}

input[type="text"]{

color:transparent;

text-shadow:000#000;

padding:6px12px;

width:60px;

cursor:pointer;

}

input[type="text"]:focus{

outline:none;

}

input:focus+ div#content{

display:block;

}

The first block of CSS hides our content when it is initially loaded.

The second block of CSS makes our text input look like a button. The most important part here is the first line setting the font color to transparent. In a normal text input, you will see a cursor appear when you click on it. In our case, we want to make it invisible so our text input behaves more like a button.

The third block uses the :focus pseudo-class but the purpose, again, is to make it behave more like a button by hiding the outline when input box is in focus.

The last CSS block ties everything together. The selector has two parts separated by the plus sign:

1) input:focus – This selects for the input box when it is in focus (or when a user clicks on it).
2) div#content – This selects for the content div that is currently hidden.

The “+” is the adjacent sibling selector and it will select only the specified element (div#content) that immediately follows the former specified element (input:focus). In other words, if the input box is in focus, select the div with ID=content and make it visible!

Note that if you click elsewhere in the browser, it will make the content hidden again because the input box no longer has focus.

Here is another that does the opposite. It starts with the content visible and hides when the “button” gains focus:

The other state we can use to hide content is when an element gains the hover state. This is when the mouse or pointer is hovering over an element. We can use the :hover pseudo-class to select for this and hide content. Here is the demo:

The HTML is simple:

<button>HOVER OVER ME</button>

<div id="content">

and the content will show.

</div>

There is a button and a div with the content we want to show or hide.

The CSS looks very much like before:

div#content{

display:none;

}

button:hover+ div#content{

display:block;

}

The first block hides the content when the page initially loads.

The second block uses the :hover pseudo-class and the adjacent sibling selector (+). It’s basically telling the browser “if the user is hovering over the button, select the div with ID=content and make it visible!”

For completeness, here is the same demo but the content initially showing:

That’s it! If Javascript is at your disposal, these are some Javascript and jQuery tutorials you can use to hide or show content.

If you found that my code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers! OR…you can sign up for a free Dropbox account using my referral link =) If you are not aware of what Dropbox is, it is the most awesomest online backup application there and so much more…all for free.

I was recently working on a custom WordPress widget where I wanted to include an image in the widget title. For security reasons, WordPress sanitizes the html so it was not working for me. I searched and searched on the internets but ran into solutions that were bulky and didn’t work for me. After looking into the text widget source code which allows html, I found this useful filter:

It’s been years since my last tutorial, so I’m coming out of retirement for this one :) This tutorial is in response to a request to do a simple slideout menu so here goes.

In this demo, we’ll have a menu on the left side that is hidden at first with a button that will toggle the sliding effect.

Let’s start with the HTML. It’s just a button and a container that’s holding an unordered list of items. Nothing too exciting to see here.

Next is our CSS. The button is floated to the right so it doesn’t get in the way of our menu which is on the left side. The first 2 lines of CSS for the container sets the background color orange and width to 250 pixels. The rest of the CSS allows us to manually position the container exactly 250 pixels to the left of the document. Since it’s original position was on the left side and the width of the container is exactly 250 pixels, we basically hid it off the screen on the left side. This image explains better what the CSS positioning does.

Now for some jQuery magic to tie all this together. The first line of the JavaScript caches or saves the container element because we refer to it more than once. It’s just good practice and it speed things up a bit although it’s negligible in this case. The 2nd line of code checks how far left we’ve moved the container so the function remembers where the container needs to go in order to hide it again when a user toggles the button. This number is saved into the leftVal variable. This could have been hardcoded to -250 but it makes it more difficult to maintain the code in case you decide to change the width of the container.

The rest of the script instructs the browser on what it should do when a user clicks on the button. In other words, it binds an event handler to the click JavaScript event. The button will sit there on the page and listen for a click event and execute a function that is passed into it. Here is what the function does. It creates a new variable called animateLeft which will be used to tell jQuery where the container should be. This variable is dynamic depending on what state the container is in. If the left position of the container is equal to 0, this means that it is visible and on the screen.

In this case, the animateLeft variable is set to the value of leftVal because we want to move it back to it’s original position (which is hidden -250 pixels to the left side). If the left position of the container is not equal to 0, this means that it is in the hidden position. To make it visible, we’ll need to set the animateLeft variable equal to 0.

The last line of the JavaScript uses the jQuery animate() function which animates specific CSS properties. In our case, we want to animate the left position of our container which will give it a sliding effect. Do we know how far left we need to animate? Yes! We saved it in the animateLeft variable earlier in our if statement.

And that wraps it up for this tutorial! If you would like to see a demo for a menu on the right side, check it out here.

If you found that this code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers!

Note: If you have an issue with your code and would like help, please create a JSFiddle and send me the link with your detailed issue.

If you had to choose a drink, what would you choose:
<ul>
<li><a href="/demo/demo-show-hide-based-on-url.html?option=coke">Coke</a></li>
<li><a href="/demo/demo-show-hide-based-on-url.html?option=bubble-tea">Bubble Tea</a></li>
<li><a href="/demo/demo-show-hide-based-on-url.html?option=milk">Milk</a></li>
</ul>

It is a simple list of options for a user to select and the key is in the linking url. There is an option parameter where we are passing over the user’s selected option. The option values (coke, bubble-tea, and milk) will map to their respective div ids on the following page that we will dynamically hide or show.

Line 1 imports the jQuery library from Google’s content distribution network (CDN). There are a couple of reasons why you should use CDNs including decreased latency and increased parallelism. If you are interested in reading the details, here is a nice post.

Line 4 assigns the default div id that will be shown which in this case is coke.

Lines 5-6 parses the option value from the url information.

Line 7 calls the showDiv() function and passes the option value as an argument.

In line 10 of the showDiv() function, we hide all the divs in case there are any that are opened. We do this using the jQuery class selector where we select all the elements with the boxes class.

Line 11 will use the id (e.g. #) jQuery selector using the option parameter that was passed over and show the element via the jQuery .show() method.

Here is the HTML code for the second page with our dynamic displayed content:

<div class="boxes" id="coke">Coke is awesome!</div>

<div class="boxes" id="bubble-tea">Bubble tea is da bomb!</div>

<div class="boxes" id="milk">Milk is healthy!</div>

<p>

I change my mind:

<ul>

<li><a href="javascript:showDiv('coke')">Coke</a></li>

<li><a href="javascript:showDiv('bubble-tea')">Bubble Tea</a></li>

<li><a href="javascript:showDiv('milk')">Milk</a></li>

</ul>

</p>

<a href="/demo/demo.html">Back to main page</a>

We begin with the divs, each with their respective ids (coke, bubble-tea, milk). We then re-list our options on this page as well. The links here do not link to another page though. Instead, they call the showDiv() function and pass over the selected option.

If you found that my code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers! OR…you can sign up for a free Dropbox account using my referral link =) If you are not aware of what Dropbox is, it is the most awesomest online backup application there and so much more…all for free.

If there is anything I hate more than the smell of durian, it is having to deal with date range calculations in JavaScript. Luckily though, we have the Datejs JavaScript Date Library to prevent us from having to pull our hair out.

Mission

I was recently faced with having to implement a date range drop-down menu very similar to of the one that is beautifully implemented in Google Adwords:

The select input element had to return 3 pieces of information: The name of the option, start date, and end date of the selected option.

Here are the specific options that I had to implement for the date ranges:

Surprisingly, it took me a long time to find this solution so I decided to post it for anyone who had a situation similar to mine.

Let’s say you have the following 2D associative array in PHP of fruits and their corresponding prices and you want to have them sorted by price:

$fruits=array([0]=>array(['product']=>'banana',['price']=>2.99),[1]=>array(['product']=>'apple',['price']=>1.99),[2]=>array(['product']=>'durian',//these smell by the way - i do not know how people can like them =)['price']=>19.99),[3]=>array(['product']=>'starfruit',//not too stinky but still stinky nonetheless['price']=>5.99));

I recent ran into an interesting IE bug involving the following bit of html code:

<a href="javascript: void(0);" onclick="dosomething();">click me</a>

I honestly did not write this one but I will leave names out of this to protect the innocent =)

The void(0) JavaScript code is usually used to prevent loading or reloading of the page when the user clicks the link.

What we were trying to do here was have the dosomething JavaScript function execute when a user clicks on the link. This works fine in FireFox, Chrome, Safari but not IE. When a user clicks on the link in IE, nothing happens: i.e. (no pun intended) the JavaScript does not execute.

It took us a good amount of time to realize what the issue was with IE. It turns out that the void(0) function was preventing the onclick event to fire.

Although it may not be pretty, this is what we ended up doing and it appears to be cross-browser friendly:

Thanks Ulrich for the suggestion! In this version, if a user has JavaScript disabled, a click on this link will take them to the [alternative link]. If JavaScript is enabled, then dosomething() will execute and the return false will prevent the browser from going to the [alternative link].

Let’s say you have the following PHP code that extracts the date from the times table in your MySQL database. The date is of timestamp type which has the following format: ‘YYYY-MM-DD HH:MM:SS’ or ‘2008-10-05 21:34:02.’

Let’s say you have the following table called votes that keeps track of how people voted and you want a query to count the number of votes for you instead of having to loop through all the rows with a counter in PHP.

JavaScript has a built-in function called confirm which takes a string argument that poses the question to the user and gives them the option to click the OK or Cancel buttons and returns true if the user clicks OK.

Have you ever had to access a parent node from a given child node? In this example, we are going to traverse up the DOM tree starting from the button to look for the parent node with the name attribute itsMe.

This is a simple example of implementing a calculator with JavaScript and HTML. This calculator will only have the division, multiplication, addition, and subtraction operators but you can easily tack on more functions if needed.

1) Find – If only the Find box is filled in, then the findMyText() JavaScript function will just perform a find for the div that is given. If there is a match, the text will be highlighted and marked in bold.

2) Find and Replace – If both the Find and Replace boxes are filled in, then the findMyText() JavaScript function will do just that.

There is a rare need for this type of functionality but I have found myself in a couple of situations where I needed it. Here is a quick demo of a button click that is simulated from another event handler. In this case, the button click is invoked by checking a checkbox.

Are you looking for a simple way to verify a form that you have? The example below demonstrates some of the common techniques used in verifying a form. Test out the form by leaving at least one of the fields blank before you submit the form.

The Document Object Model (DOM) allows for dynamic styling because it makes all HTML elements and attributes readily accessible using JavaScript. Here is a simple demo of how powerful this technology can be:

Not all forms are meant to be static. Sometimes, you want to allow the users to add certain parts of the form as they need them. Here is a nice example of dynamically adding inputs to your form as users need them. In addition, an input limit has been implemented in the script and it is set to 3.

I have found myself in a couple of situations where I needed a simple dynamic javascript menu where the user would make a selection from one select list and depending on what the user selected from the first select list a second list would offer further options. Here is a perfect example: