How to hide or show content based on CSS

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:

  1. <input type="text" value="CLICK TO SHOW CONTENT">
    
  2. <div id="content">
    
  3.     and the content will show.
    
  4. </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:

  1. #content {
  2.   display: none;
  3. }
  4. input[type="text"]{
  5.     color: transparent;
  6.     text-shadow: 0 0 0 #000;
  7.     padding: 6px 12px;
  8.     width: 60px;
  9.     cursor: pointer;
  10. }
  11. input[type="text"]:focus{
  12.     outline: none;
  13. }
  14. input:focus + div#content {
  15.   display: block;
  16. }

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:

  1. <button>HOVER OVER ME</button>
    
  2. <div id="content">
    
  3.   and the content will show.
    
  4. </div>

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

The CSS looks very much like before:

  1. div#content {
  2.   display: none;
  3. }
  4. button:hover + div#content {
  5.   display: block;
  6. }

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, for some reason, Javascript is not at your disposal, these are some of the CSS tricks 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.





Adding html to your WordPress widget title

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:

apply_filters( 'widget_text', empty( $instance['text'] ) ? '' : $instance['text'], $instance );

I adapted it to my WordPress plugin for the widget like so:

$instance['title'] = '<img src="https://www.some_website.com/images/logo.png">My Logo';
apply_filters( 'widget_text', $instance['title'] );

And that does it!

A simple slideout menu tutorial using jQuery

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.

Screen Shot 2015-10-23 at 10.21.35 PM

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.

Screen Shot 2015-10-23 at 10.59.43 PM

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.

How to hide or show content based on links or urls via JavaScript/jQuery

I have received many requests for a tutorial that shows how to hide or show content based on links or options that a user picks and reflected on a different page so here it is =)

You can see a working demo here.

Here is the plain HTML:

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.

Here is the JavaScript/jQuery code that executes on the linking page:

  1. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
  2. <script type="text/javascript">
  3. $(document).ready(function() {
  4. 	var option = 'coke';
  5. 	var url = window.location.href;
  6. 	option = url.match(/option=(.*)/)[1];
  7. 	showDiv(option);
  8. });
  9. function showDiv(option) {
  10. 	$('.boxes').hide();
  11. 	$('#' + option).show();
  12. }
  13. </script>

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:

  1. <div class="boxes" id="coke">Coke is awesome!</div>
    
  2. <div class="boxes" id="bubble-tea">Bubble tea is da bomb!</div>
    
  3. <div class="boxes" id="milk">Milk is healthy!</div>
    
  4. <p>
    
  5. 	I change my mind:
    
  6. 	<ul>
    
  7. 		<li><a href="javascript:showDiv('coke')">Coke</a></li>
    
  8. 		<li><a href="javascript:showDiv('bubble-tea')">Bubble Tea</a></li>
    
  9. 		<li><a href="javascript:showDiv('milk')">Milk</a></li>
    
  10. 	</ul>
    
  11. </p>
    
  12. <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.





How to dynamically remove elements from the DOM via jQuery


jQuery is an awesome JavaScript library that can do some very heavy lifting in very small amounts of code. Take the example below where we are simply removing a div element from the DOM.

Demo
Remove me by clicking the button below.


Continue reading How to dynamically remove elements from the DOM via jQuery

JavaScript Date Ranges/Calculations with Datejs



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:

Google Adwords Date Range Pull-Down Menu

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:

  • This month to date
  • This quarter to date
  • Last 7 days
  • Last 30 days
  • Last 365 days
  • Last week (Mon to Sun)
  • Last full month
  • Last full quarter
  • Last full year

The Plan

Continue reading JavaScript Date Ranges/Calculations with Datejs

How to hide, show, or toggle your div with jQuery


Hiding and showing content is MUCH easier with the magic of jQuery. Here is a simple demo of the jQuery .toggle() function.

Demo

Toggle Button

The content in this div will hide and show (toggle) when the toggle is pressed.

Here is the JavaScript needed to run this demo:

  1. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  2. <script type="text/javascript">
  3. function toggleDiv(divId) {
  4.    $("#"+divId).toggle();
  5. }
  6. </script>

Continue reading How to hide, show, or toggle your div with jQuery

Parsing XML data from hostip.info API service with PHP

If you ended up here, then you most likely experienced what I did in trying to figure out how to parse the XML data from the hostip.info web API service.

Basically, it is down to the namespaces that are not accessible by normal means.

Here is the basic XML response from a typical hostip.info call such as http://api.hostip.info/?ip=[IP-ADDRESS]

  1. <?xml version="1.0" encoding="ISO-8859-1" ?>
  2. <HostipLookupResultSet version="1.0.1" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.hostip.info/api/hostip-1.0.1.xsd">
  3.    <gml:description>This is the Hostip Lookup Service</gml:description>
  4.    <gml:name>hostip</gml:name>
  5.    <gml:boundedBy>
  6.       <gml:Null>inapplicable</gml:Null>
  7.    </gml:boundedBy>
  8.    <gml:featureMember>
  9.       <Hostip>
  10.          <ip>12.215.42.19</ip>
  11.          <gml:name>Sugar Grove, IL</gml:name>
  12.          <countryName>UNITED STATES</countryName>
  13.          <countryAbbrev>US</countryAbbrev>
  14.          <!-- Co-ordinates are available as lng,lat -->
  15.          <ipLocation>
  16.             <gml:pointProperty>
  17.                <gml:Point srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
  18.                   <gml:coordinates>-88.4588,41.7696</gml:coordinates>
  19.                </gml:Point>
  20.             </gml:pointProperty>
  21.          </ipLocation>
  22.       </Hostip>
  23.    </gml:featureMember>
  24. </HostipLookupResultSet>

Continue reading Parsing XML data from hostip.info API service with PHP

Groupon – Commission Junction (CJ) WordPress Widget Plugin that Displays Local Deals

I have developed a Groupon -Commission Junction (CJ) WordPress Widget Plugin that automatically displays the local deals for the visitor. It allows you to plugin your Commission Junction (CJ) PID account number and display the local links according to the visitor IP address. The demo of this widget is currently running on this site in the upper right-hand corner.
Continue reading Groupon – Commission Junction (CJ) WordPress Widget Plugin that Displays Local Deals

Sorting 2D associative arrays in PHP

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
        )
);

Continue reading Sorting 2D associative arrays in PHP

Dynamic or on-the-fly percentage calculations with JavaScript


Here is a simple JavaScript function that does dynamic or on-the-fly percentage calculations.

Demo




You have saved 50 %

Continue reading Dynamic or on-the-fly percentage calculations with JavaScript

The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag

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:

<a href="<?=$_SERVER['PHP_SELF'];>#" onclick="dosomething(); return false;">click me</a>

Update: Here is an updated version of the code that accounts for users with JavaScript disabled:

<a href="[alternative link]" onclick="dosomething(); return false;">click me</a>

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].

Anyway, I hope this helps someone out there in the universe.

How to randomly order or select rows in a MySQL query

I was looking for a way to order the rows randomly in a MySQL query and the solution was not easy for me to come by. I am posting the solution here in hopes of helping others.

  1. SELECT * 
  2. FROM my_table
  3. ORDER BY RAND()

RAND() returns a random floating-point value but functions to randomly order the selection of rows in the above usage.

If you combine the query with LIMIT, you will end up with a random selection of rows from your table.

  1. SELECT * 
  2. FROM my_table
  3. ORDER BY RAND()
  4. LIMIT 3

Assuming you have more than 3 rows in your table, you will always get 3 random rows from the query.

How to convert MySQL timestamp to PHP date type

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.’

  1. $res = mysql_query("SELECT date FROM times;");
  2. while ( $row = mysql_fetch_array($res) ) {
  3.    echo $row['date'] . "<br />";
  4. }

Continue reading How to convert MySQL timestamp to PHP date type

How to count values with MySQL queries

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.

person vote
obama yes
mccain no
obama yes
obama no
mccain yes
obama yes
obama yes
obama no
mccain no

Continue reading How to count values with MySQL queries

How to confirm or prompt user for input via JavaScript


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.

Demo
green box

yellow box


Continue reading How to confirm or prompt user for input via JavaScript

How to find and access parent nodes via JavaScript


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.

Demo
My name is notMe

My name is itsMe

My name is notMeEither

My name is tryAgain

My name is sorryNotMe

My name is nopeSorry

Continue reading How to find and access parent nodes via JavaScript

How to loop through checkboxes or radio button groups via JavaScript


Do you have a form with checkboxes or radio buttons that you would like to loop through via JavaScript? This JavaScript function will do just that!

Demo
I like to program in:

PHP

Perl

Ruby

ASP


I like to eat:

Snickers

Hershey's

M&M's

Nerds


I like to drink:

Coke

Gatorade

Pepsi

Milk


Continue reading How to loop through checkboxes or radio button groups via JavaScript

How to create your own customized calculator via JavaScript

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.

Demo

Continue reading How to create your own customized calculator via JavaScript

How to dynamically add content to a div and store the content to a cookie via JavaScript


This is an example of adding dynamic content via JavaScript by allowing the user type in the actual content.

Demo
Content to be added:


Your content will be added dynamically below:

Continue reading How to dynamically add content to a div and store the content to a cookie via JavaScript

How to validate email format via JavaScript


This JavaScript demo verifies that an email address is in the correct format and that the user has typed in the same address in both fields to prevent mistyping of the address. I have borrowed the regex for verifying the correct email format from a different site.

Demo
Email:

Please type in your email again:

Continue reading How to validate email format via JavaScript

How to dynamically remove/delete elements via JavaScript


This post is in response to one of the comments on have received regarding the removal of elements via JavaScript. I have taken the original function posted and edited it a little bit for the demo.

Demo
I am the parent div.

I am a child div within the parent div.

 


Continue reading How to dynamically remove/delete elements via JavaScript

How to find and replace text dynamically via JavaScript


This is a neat little script that demonstrates two things:

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.

Demo
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Find
Replacment


Continue reading How to find and replace text dynamically via JavaScript

Simulate a button click via JavaScript

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.

Demo

Check the box to simulate a button click


Continue reading Simulate a button click via JavaScript

JavaScript to select all or none of the checkboxes in a form


Here is a quick demo of the select all or none JavaScript function that automatically toggles all of your checkboxes in a given form.

Demo
My favorite programming/scripting language is:

Select All | None

JavaScript

Perl

PHP

C++

Continue reading JavaScript to select all or none of the checkboxes in a form

Dynamically edit font styling of HTML content via JavaScript

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:

Demo
Hello world!







Continue reading Dynamically edit font styling of HTML content via JavaScript

How to dynamically add form elements via JavaScript



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.

Demo
Entry 1


Continue reading How to dynamically add form elements via JavaScript

How to hide, show, or toggle your div

Are you trying to find a way to hide and show your content? The demo below shows a simple yet elegant way of toggling your content and toggling the control text via Javascript and styling.

Demo
click image to expand/collapse==>

This demo uses plus and minus images for hiding and showing your div dynamically via JavaScript. This content will toggle.

We will cover how to implement this example later on in the tutorial but first let’s start with a simple example.

Demo

show < == click here

Continue reading How to hide, show, or toggle your div

Dynamic Country State Javascript Menu Example


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:

Demo

Country:

State/Province:

Country value:

 

State/Province value:
 

Continue reading Dynamic Country State Javascript Menu Example