Oct 16, 2009

A Cool Dynamic Link Trick

While programming my individual project I was tasked with trying to dynamically add an html link to the web page using javascript. I tried inserting the code in javascript as I would in html but found that javascript did not like the tags within the html code (even when you put it in quotes). I even tried breaking up the code in javascript by using many quoted parts with +'s to insert into my html dynamically and I was still unsuccessful. To fix this issue I decided to do something different.

Steps:
1. I first created a div inside my .html file that will house the .


2. I then created an anchor inside the div with only the "id" of the tag provisioned. href needs to be blank quotes and their should be no text that shows the link on the page.


By doing this, you are essentially creating a placeholder for your dynamic link on your page. If you were to post your updated .html file you will see that there is no link displayed on the page to click.

The second part of this is to use javascript to insert your desired link dynamically into the you have created. I have included code from my .js file to show you how I did this. Place this code inside a function inside your javascript.
1. The first line of code gets the id of the tag and inserts into the .innerHTML field the link the user would see on the web page to click on.

2. The second line of code sets the href of the tag to point to http: address. In my case I have it pulling dynamically from a yahoo api. You can easily put in a static link such as http://is449w.blogspot.com/ .

3. The third line of code sets the target of the tag to launch a new page when the link is click on.


When your javascript function runs, the link will dynamically show up on the web page. You can see this in action at http://people.emich.edu/jguest/IS449W/indiv2/default.html . Just click on a link on the left hand side and you will see my dynamic link to buy a book show up on the right hand side.

Hopefully this will help you in your endeavors with your dynamic websites. Although I found this trick out on my own, I did a quick google search and found sites like http://www.codelifter.com/main/tips/ that offer cool tips and code you can use to spice up your web page.

Enjoy!!

2 comments:

  1. That's pretty cool. I never knew we had to have a dynamic link in our individual assignment. I will probably steal your post and apply it to my page somehow. thanks for the post.

    ReplyDelete
  2. This is really nice. Thats an idea how to realize some ideas on my project which I thought might be difficult to realize. Thanks for the post!

    ReplyDelete