Quick Answer: Add Random Dates to MySQL Database

January 30, 2008

Looking for a way to add random dates to a column in one of your MySQL tables?

I ran across this problem and found a straightforward solution. By utilizing str_to_date(), concat(), floor() and rand() you can specify a random date for a column.

update  mytable
set     mycolumn = str_to_date(
                               concat(
                                      floor(1 + rand() * (12-1)), 	/* Generate a random month */
                                      '-',
                                      floor(1 + rand() * (28 -1)), 	/* Generate a random day */
                                      '-',
                                      '2008'
                                      ),
                                '%m-%d-%Y'
                                );
Advertisements

Quick Answers: Dynamically Apply a Border to all IMGs in the DOM

January 2, 2008

Many people have asked me to put up a Quick Answer that would allow them to dynamically apply a border to all IMG elements in the DOM.

Before …

border-002.png

After …

border-001.png

To dynamically apply CSS padding and borders to all IMG elements in the DOM, you can use the following Javascript function:

<html>
  <head>
    <script language="Javascript">
      function drawIMGBorder()
      {
        //Create a reference of all IMG elements in DOM
        var imgs = document.getElementsByTagName('img');

        //Loop through each of the IMG elements
        for(i = 0; i <= (imgs.length -1); i++)
        {
          //Apply CSS padding to current IMG
          imgs[i].style.padding = "2px";
          //Apply CSS border to current IMG
          imgs[i].style.border = "2px Solid #cacaca";
        }
      }
    </script>
  </head>
<body onLoad="drawIMGBorder();">
  <img src="picture1.jpg" border="0" />
  <img src="picture2.jpg" border="0" />
</body>
</html>

In this example the Javascript function is called when the page loads, but this can easily be modified to another Javascript event.


Quick Answers: How many images are in the DOM?

January 2, 2008

You can dynamically determine the number of images (<img>) on a web page by using Javascript.

var imgCount = document.getElementsByTagName('img').length

To create a reusable function you can use the following code:

function countAllImages()
{
var imgCount = document.getElementsByTagName('img').length;
return imgCount;
}

Quick Answer: Count the Number of Child Elements in DOM

December 30, 2007

Sometimes I come across the need to count the number of child elements in any given area of the DOM. Below is an example of how to count the number of elements by using the getElementsByTagName() function.

<html>

<head>
<script language = "Javascript">
function countChildElements(parent, child)
     {
          var parent = document.getElementById(parent);
          var childCount = parent.getElementsByTagName(child).length;
          alert(childCount);
     }
</script>
</head>
<body>
<ul id = "listing">
 <li>List Item 1</li>
 <li>List Item 2</li>
 <li>List Item 3</li>
</ul>
<input type = "button" value = "Count <li>" onClick="countChildElements('listing','li');" />
</body>
</html>

When you click the button, the browser will alert you to the number of child <li> elements to the “listing” <ul>.


Quick Answer: Dynamically Adding a Hyperlink to the DOM

December 29, 2007

Javascript is capable of appending child elements to the DOM of a web page dynamically. This quick answer demonstrates one way to append a <a> element to a <div>.

How to append a hyperlink to the DOM is relatively straight forward.

  1. First reference the parent node to add the new child element to
  2. Create a new <a> element using document.createElement(‘a’);
  3. Set the “href” attribute value for the <a>
  4. Create a new text node using document.createTextNode();
  5. Append the text node to the <a> element
  6. Finally, append the new <a> element to the parent node

<html>
  <head>
    <script language="Javascript">
      function appendLink()
      {
        //Get the element that we want to append to
         var divEl = document.getElementById('link_div');
        //Create the new <a>
        var aElem = document.createElement('a');
        aElem.href="http://www.google.com";
        //Create a text node to hold the text of the <a>
        var aElemTN = document.createTextNode('link to Google.com');
        //Append the <a> text node to the <a> element
        aElem.appendChild(aElemTN);
        //Append the new link to the existing <div>
        divEl.appendChild(aElem);
      }
    </script>
  </head>
  <body>
    <input type="button" value="Add Link" onClick="appendLink();">
    <div id="link_div"></div>
  </body>
</html>

Web Browser Output of code before button is clicked:

Dynamically Adding a Hyperlink 001

Web Browser Output after button is clicked:
Dynamically Adding a Hyperlink 002


Dynamically Modifying the DOM with Javascript: CD Collection App Post 01

December 23, 2007

In this series of posts, I will be attempting to build a simple application that will allow me to catalog my CD collection. Whenever possible I will be using Javascript to modify the DOM of the application to respond as close to a desktop application as possible.

Let’s create a simple HTML list to display the tracks of a CD.
index.html …

<ol id="disc_1_tracks">
  <li id="disc_1_track_1">Disc 1`Track 1</li>
  <li id="disc_1_track_2">Disc 1 Track 2</li>
</ol>

To accommodate the dynamic functionality of our new track list, we can add a temporary <a> to add additional tracks to the list.
index.html modified …

<ol id="disc_1_tracks">
  <a href="">Add Track to Disc 1</a>
  <li id="disc_1_track_1">Disc 1`Track 1</li>
  <li id="disc_1_track_2">Disc 1 Track 2</li>
</ol>

Now we are ready to build some Javascript functions that will add new tracks to the disc dynamically.
index.html modified …

<html>
  <head>
    <script language="Javascript">
      function addNewTrack(disc)
      {
        //Purpose: Adds a new track <li> to the current disc <ol>
        var currentDisc = document.getElementById('disc_' + disc + '_tracks');

        var trackLI = document.createElement('li');
        trackLI.id = 'disc_' + disc + '_track_' + (countTracks(disc) + 1);

        var trackLITN = document.createTextNode("Disc " + disc + " Track " + (countTracks(disc) + 1));

        trackLI.appendChild(trackLITN);
        currentDisc.appendChild(trackLI);
      }

      function countTracks(disc)
      {
        //Purpose: Counts the number of tracks for the current disc

        var discToCount = document.getElementById('disc_' + disc + '_tracks');
        //Count the child <li>s
        var trackCount = discToCount.getElementsByTagName('li').length;
        return trackCount;
      }
    </script>
  </head>
<body>

<ol id="disc_1_tracks">
  <a href="Javascript:addNewTrack(1);">Add Track to Disc 1</a>
  <li id="disc_1_track_1">Disc 1`Track 1</li>
  <li id="disc_1_track_2">Disc 1 Track 2</li>
</ol>

</body>
</html>

The two new Javascript functions are addNewTrack() and countTracks(). Our <a> tag in the <body> has been modified to “Javascript:addNewTrack(1);”. This simply allows us to use a hyperlink to call our Javascript function. Now let’s go through the two functions in greater detail.

Step by step tasks of addNewTrack():

  1. By using getElementById() we create the currentDisc element which contains all the references needed for the current disc.
  2. We then create a new <li> element and set its id attribute. You will notice that we call the countTracks() function to determine the number of the new track we are creating (I will explain this more in the step by step walkthrough of the countTracks() function.
  3. To add some text to the new<li> we create a new textnode (trackLTTN), and set the text we want to display.
  4. With the new <li> element we first append the textnode (trackLTT) as a child.
  5. Finally we add the <li> element to the currentDisc as a child.

Step by step tasks of countTracks():

  1. Again using the getElementById(), we create an object to reference the current disc.
  2. Then we create a variable that is the length (or count of elements) of all the <li> elements within our discToCount object.
  3. Finally we return the value of our trackCount variable.

Below is a screen shot of index.html in action:

DOM Example 001 Add Tracks to Disc

As you can see, each time the “Add Track to Disc 1” hyperlink is clicked, the javascript will modify the DOM and append a new <li> to the target <ol>.

Before we move on to extending the functionality, lets enhance the list by including the capability to define the name of the track. This can be accomplished by adding a text input field to the <li>.
index.html modified …

function addNewTrack(disc)
      {
        //Purpose: Adds a new track <li> to the current disc <ol>
        var currentDisc = document.getElementById('disc_' + disc + '_tracks');

        var trackLI = document.createElement('li');
        trackLI.id = 'disc_' + disc + '_track_' + (countTracks(disc) + 1);

        var trackLIInput = document.createElement('input');
        trackLIInput.type = "text";
        trackLIInput.value = "Disc " + disc + " Track " + (countTracks(disc) + 1);
        trackLIInput.name = "disc_" + disc + "_track_" + (countTracks(disc) + 1) + "_name";
        trackLIInput.id = "disc_" + disc + "_track_" + (countTracks(disc) + 1) + "_id";

        trackLI.appendChild(trackLIInput);
        currentDisc.appendChild(trackLI);
      }

By changing our addNewTrack() function we now have a new text input box for each new track that is added to the list.

Here is an updated screenshot:

DOM Example 002 Add Tracks to Disc with text input

Things are starting to function dynamically. Post 2 will further expand upon our Javascript and enhance our client side application.