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
2009-11-09 09:58:45
Con you be clear with the answer in detail.
i2ijeya
2009-11-09 10:00:31
Will this work cross-browser?
Russ Cam
2009-11-09 10:03:06
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
2009-11-09 10:20:35
+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
2009-11-09 10:01:28
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
2009-11-09 10:07:00
first of all: inline javascript is a bad idea. second: using href to do javascript is even worse. bad, bad solution.
peirix
2009-11-09 10:13:31
First time i gave a idea thats all. I dint tell to add script tag inline. Here is my edited script.
RSK
2009-11-09 10:31:22
Thank you satish, This is working well. thanks and thanks for everyone for their valuable comments and answers...
i2ijeya
2009-11-09 10:38:49
+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
2009-11-09 10:02:07
+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
2009-11-09 10:03:24
@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
2009-11-09 10:24:35
You can, by the way call the 'e' whatever you like. Most tutorials go with 'event' here.
Boldewyn
2009-11-09 10:26:59