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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.