-3

I have written a script which should change a Link by clicking on an element. But it doesn't work. Can anyone help me out?

<!DOCTYPE html>
<html>
<h2 id="http://www.google.com" onclick="changeLink(google);" name="google">Google</h2 >
<h2 id="http://www.yahoo.com" onclick="changeLink(yahoo);" name="yahoo">Yahoo</h2 >
<h2 id="http://www.duckduckgo.com" onclick="changeLink(duckduckgo);" name="duckduckgo">DuckDuckGo</h2 >


<a href="http://www.example.com" target="_blank" id="link">LINK</a> //should change the href after click on google, yahoo etc.

<script>
   function changeLink(x){
       document.getElementById('link').href=document.getElementsByName(x)[0].id;
   }

</script>

</body>
</html>
the
  • 21,007
  • 11
  • 68
  • 101
Andreas Schantl
  • 121
  • 1
  • 11

2 Answers2

0

Instead of using the string represents the name as the function argument, you're currently using undefined variables.

You have the change your HTML as such:

<h2 id="http://www.google.com" onclick="changeLink('google');" name="google">Google</h2 >
<h2 id="http://www.yahoo.com" onclick="changeLink('yahoo');" name="yahoo">Yahoo</h2 >
<h2 id="http://www.duckduckgo.com" onclick="changeLink('duckduckgo');" name="duckduckgo">DuckDuckGo</h2 >

(Mind the single quotes)

uri2x
  • 3,162
  • 1
  • 11
  • 25
  • There are countless number of ways to achieve the same result, some more efficient than others. However in our little corner of the web, the guy wanted to understand what's wrong with *his* code. – uri2x Sep 20 '15 at 17:45
  • Haha yea apparently :D – Jordan Davis Sep 20 '15 at 17:46
0

This is the most efficient way to achieve it and best performance wise by declaring a static JSON object to initialize the values.

Here is the JSFiddle Demo

//CODE

<!DOCTYPE html>
<html>
<head>
<style>
h2:hover{
    color: blue;
    cursor: pointer;    
}   
</style>
<script>
//JSON OBJECT LOADED ON DOC INIT
var sites = {
    "google": "http://www.google.com",
    "yahoo": "http://www.yahoo.com",
    "duck": "http://www.duckduckgo.com"     
};
function changeLink(site){
    document.getElementById("target").href = site;
    document.getElementById("target").innerHTML = site;
}
</script>
</head>
<body>
    <h2 onclick="changeLink(sites.google);">Google</h2>
    <h2 onclick="changeLink(sites.yahoo);">Yahoo</h2>
    <h2 onclick="changeLink(sites.duck);">DuckDuckGo</h2>
    <a href="http://www.example.com" target="_blank" id="target">http://www.example.com</a> 
</body>
</html>
Jordan Davis
  • 1,485
  • 7
  • 21
  • 40