Link to home
Start Free TrialLog in
Avatar of 2toria
2toriaFlag for United Kingdom of Great Britain and Northern Ireland

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:-

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

Open in new window


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
Avatar of Atique Ansari
Atique Ansari
Flag of India image

You can use onclick attribute of image.
Please find the attached code for the same.

 
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';
img.onclick = 'javascript:alert("hi")';

Open in new window

You can do it using jQuery also.
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>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of COBOLdinosaur
COBOLdinosaur
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial