I have a button that I'm trying to hide once clicked. Also I just don't want to hide it I want it to style='display:none' once clicked.
4 Answers
<button onclick="this.style.display='none';">a button</button>
see example: http://jsfiddle.net/uWfYk/
3 Comments
I Hate Lazy
@user1480167: Just add
this.style.display="none"; to that code.nonopolarity
my answer uses
attachEvent or addEventListener so that multiple handlers can be usedKris
@動靜能量's answer looks a lot better than mine, I was just trying to keep it simple here.
Update 2020:
With addEventListener() and querySelector() being supported in all major browsers, it can just be
document
.querySelector('#the-important-button')
.addEventListener('click', ev => ev.target.style.display = 'none');
<button id="the-important-button">Click</button>
Answer in 2012:
To make it unobtrusive and work on earlier IE and other modern browsers:
the HTML:
<button id="the-important-button">Submit</button>
JavaScript:
var theButton = document.getElementById('the-important-button');
function hideTheButton() {
this.style.display = 'none';
}
function addEvent(target, type, handler) {
if (target.addEventListener) {
target.addEventListener(type, handler, false);
} else if (target.attachEvent) {
target.attachEvent('on' + type, function() {
return handler.call(target, window.event);
});
} else {
target['on' + type] = handler;
}
}
addEvent(theButton, 'click', hideTheButton);
Note that addEvent is a generic function that works well on earlier IE and other modern browsers. You can add other events similar to the last line of code above.
Sample on http://jsfiddle.net/W37Fb/5/
4 Comments
I Hate Lazy
Beware of
.attachEvent. It will set this to the window in the hideTheButton function. To make it work the same, you need to wrap an anonymous function around the hideTheButton call and invoke it like this: hideTheButton.call(theButton, window.event);I Hate Lazy
Very close, but get rid of the
event parameter for the anonymous handler, and pass window.event to the actual handler. The attachEvent doesn't pass an event object. After that, you've got my +1. :-)nonopolarity
Ah I see, I saw the Dustin Diaz's version... the first version I used was from the JavaScript Definitive Guide 6th ed, p. 461...
user1480167
thanks for your elaborate explination, and to everyone else who helped make this one...THANKS
Using jquery as follows
$("#btn").click(function(){
//do need full
$(this).fadeOut();
})
Using pure JS
5 Comments
I Hate Lazy
OP didn't mention that jQuery is used, and you don't need to load a large DOM library for simple tasks.
Sameera Thilakasiri
This is just an example how to do it in jQuery, use or not its is upto the developer.
user1480167
what do i do if i have more than one onclick?
I Hate Lazy
@user1480167: Have you loaded the jQuery library? If not, this code won't work for you.
user1480167
simple hide button when clicked but it has another onlick where it makes a div appear.