views:

122

answers:

4

I have an html page which has a link called "open". Once the link is clicked the text "open" should change to "close". How do I do this?

A: 

If elm is the link:

elm.addEventListener("click", function(){
  this.innerHTML = "close";
}, true);
Marius
Con you be clear with the answer in detail.
i2ijeya
Will this work cross-browser?
Russ Cam
no, this will not work cross-browser. attachEvent is IE's method of attaching events, addEventListener works in all others as far as I'm aware
jaywon
+1  A: 

Script

<html>
  <head>
    <script type="text/javascript">
      function open_fun() {
        document.getElementById('link').innerHTML = "<a href='javascript:clo_fun()'>CLOSE</a>";
      }
      function clo_fun() {
        document.getElementById('link').innerHTML = "<a href='javascript:open_fun()'>OPEN</a>";
      }
    </script>
  </head>
  <body>
    <div id='link'><a href='javascript:open_fun()'>OPEN</a></div>
  </body>
</html>
RSK
Satish, the above code is not working. Wats the below code do,<a href='close()'>close</a>..Why u are using "close()", what does it do?
i2ijeya
first of all: inline javascript is a bad idea. second: using href to do javascript is even worse. bad, bad solution.
peirix
First time i gave a idea thats all. I dint tell to add script tag inline. Here is my edited script.
RSK
Now u can try this, i2ijeya
RSK
Thank you satish, This is working well. thanks and thanks for everyone for their valuable comments and answers...
i2ijeya
+4  A: 
<a href="" onClick="javascript:this.innerHTML = 'close'">Open</a>

You could also call some type of toggle function for swapping the text on multiple clicks.

function toggle(lnk_obj){
    lnk_obj.innerHTML = (lnk_obj.innerHTML == 'close') ? 'open' : 'close' ;
}


<a href="" onClick="javascript:toggle(this);">Open</a>
jaywon
whers the href??
i2ijeya
there's no need to specify `javascript` with onclick events. `<a onclick="this.innerHTML ... ` is sufficient.
peirix
But the hypher link doesn't appears for the above code??
i2ijeya
@i2ijeya - that was just a basic example, i figured you could edit the HTML to suit your needs. i added href="" to the example
jaywon
+1  A: 

addEventListener is not supported in IE. If you don't need other onclick events on the link, use this:

elm.onclick = function (e) {
    this.innerHTML = "close";
};
Boldewyn
Wats 'e' in the above code?
i2ijeya
InnerHTML is evil. It is better to use nodeValue.
silent
@i2ijeya: e is the default parameter that is given to event-handling functions in FF, Opera and WebKit based browsers, an Event object.@silent: It is evil, but it is also foolproof. Using nodeValue involves testing if a firstChild exists.
Boldewyn
You can, by the way call the 'e' whatever you like. Most tutorials go with 'event' here.
Boldewyn