Welcome to WebmasterWorld Guest from 54.90.204.233

Forum Moderators: open

Message Too Old, No Replies

Correct Code For Image Hyperlink Using Javascript

javascript Image hyperlinks

     
10:23 am on Jan 22, 2018 (gmt 0)

New User

joined:Mar 21, 2016
posts:1
votes: 0


Hi

I need to create menu in my test site, and some reason it can be achieved using javascript
if in regular HTML usually we use this code, then how we do this using javascript
<a href="https://www.w3schools.com"><img src="smiley.gif" alt="Go to W3Schools!" ></a>


the next one is ,are this code is correct ?
<a href="javascript:void(0)" onClick="window.location.href='https://www.webmasterworld.com'" >www.webmasterworld.com</a>


the reason i ask this is because i read somewhere that search engine bot are unable to read some javascript
and on this test site it seems im going to use a lot of javascript code so i need to make sure they can be crawled by search engine bot

Thanks
6:00 pm on Jan 22, 2018 (gmt 0)

Junior Member from CA 

Top Contributors Of The Month

joined:Mar 2, 2017
posts:51
votes: 5


Are you having a custom code in you "onClick" event?

If you are using "onClick" just to redirect to a page why don't you use it as the first example?

<a href="https://www.webmasterworld.com" >www.webmasterworld.com</a>


If you are using some custom code in your "onClick" event, you can still use a standard href and have a custom code in your event.

<a href="https://www.webmasterworld.com" onClick="myCustomFunction()" >www.webmasterworld.com</a>


<script type="text/javascript">
function myCustomFunction(){
console.log("hello");
console.log("bye");
}

</script>
6:16 pm on Jan 22, 2018 (gmt 0)

Senior Member

WebmasterWorld Senior Member Top Contributors Of The Month

joined:Apr 1, 2016
posts:2421
votes: 647


What Johnathon said but i will add. Even if you use custom JS I would still use a standard format as in your first example and then add an event listener to listen for the click on that link and then use preventDefaut() to prevent the link from executing, then fire your code to do the redirect.

This has two advantages, one, it separates your JS from your HTML making it cleaner and easier to maintain and two if a user has disabled JS they will still be able to use the link.