2toria
asked on
Javascript: Adding links to dynamically generated images
I've been playing around with some Javascript stuff for a personal project and created this:-
http://lab.2toria.com/scrabble.php
What I would like to do is to add a link to each of the images generated on the keypress. For now it doesn't matter what the href is, I just want something like href="#" just to see it working - hopefully will be able to suss the rest out from there.
The code I'm using to generate the scrabble tiles as keys are pressed is this:-
Is there an easy way of then doing something like img.href="#"? I've tried it that way but with no luck.
Any help would be appreciated.
TIA,
Matt
http://lab.2toria.com/scrabble.php
What I would like to do is to add a link to each of the images generated on the keypress. For now it doesn't matter what the href is, I just want something like href="#" just to see it working - hopefully will be able to suss the rest out from there.
The code I'm using to generate the scrabble tiles as keys are pressed is this:-
var theLetter = document.getElementById("testtile");
var img = new Image();
//Don't run the rest of the code if non-alphabetical characters entered.
if(keynum<97||keynum>122) {
return;
}
theLetter.appendChild(img);
img.src = '/scrabbletiles/' + keynum + '.gif';
Is there an easy way of then doing something like img.href="#"? I've tried it that way but with no luck.
Any help would be appreciated.
TIA,
Matt
You can do it using jQuery also.
Please try the attached code and see if it works.
Please try the attached code and see if it works.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($)
{
var image_path = '/scrabbletiles/';
var image_ext = '.gif';
$("#element_name").live('keypress',function(keynum)
{
var keynum = e.keyCode;
//Don't run the rest of the code if non-alphabetical characters entered.
if( keynum < 97 || keynum > 122 )
{
return;
}
var append_html = '<a href="#" class="image_links" title="'+keynum+'"><img src="'+image_path+keynum+image_ext+'" alt="'+keynum+'" /></a>';
$("#testtile").append(append_html);
});
$("a.image_links").live('click', function(e)
{
e.preventDefault();
alert( 'Clicked on image ==> ' + $(this).attr('title') );
});
});
</script>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Please find the attached code for the same.
Open in new window