Jump to content

displaying an image?


spires

Recommended Posts

Hi Guys.

 

I'm new to javascript.

I'm trying to get an if statment to display different images.

 

<script type="text/javascript">

if (id==link1) 
{
document.write("<a href="#" id="link1"><img src="page GFX/New_Products/More_offers.jpg"></a>")
}
else
{
document.write("<a href="#" id="link2"><img src="page GFX/New_Products/Back_to_start.jpg"></a>")
}
</script>

 

Can someone let me know where i'm going wrong.

 

Thanks for your help

 

Link to comment
https://forums.phpfreaks.com/topic/76193-displaying-an-image/
Share on other sites

A few things...

 

1) link1 is a string, not a JS variable. Not that I know where the id variable comes from...?

2) You have quoting issues -- you can't put double quotes in a double quoted string literal, or the parser won't know where the string starts and end.

3) document.write() isn't always the best way to go.

4) You have lots of code duplication -- a hash would be better.

5) No semi-colons?

6) No functions?

 

Something like:

 

<script type="text/javascript">

var sLink = ( hLinks[id] ) ? id : 'DEFAULT';

var hLinks = {
'link1':{ 'id':'link1', 'href':'#', 'src':'page GFX/New_Products/More_offers.jpg' },
'link2':{ 'id':'link2', 'href':'#', 'src':'page GFX/New_Products/Back_to_start.jpg' },
'DEFAULT':{ 'id':'default, 'href':'#', 'src':'page GFX/New_Products/default.jpg' }
};

var sImageHTML = '<a href="'+hLinks[sLink].href+'" id="'+hLinks[sLink].id+'"><img src="'+hLinks[sLink].src+'"></a>';
document.write( sImageHTML );
</script>

 

Of course, if I were emehrkay, then writing out the HTML code would be method of an custom object ;-)

Link to comment
https://forums.phpfreaks.com/topic/76193-displaying-an-image/#findComment-385708
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.