Reputation: 83
I would like to hide Elements by class name. I found a working example that runs outside of a function. However, when I use onClick it doesn't seem to work anymore. Please take a look at the following example: http://jsfiddle.net/SkfDz/9/ Can anyone please help me?
HTML:
<input class="" name="options" id="opt1" type="radio" onClick="hideToday()"/><label for="opt1">Hide today</label>
<input class="" name="options" id="opt1" type="radio" onClick="hideToday()"/><label for="opt1">Hide today</label>
<div class="today">TODAY</div>
<div class="today">TODAY</div>
<div class="today">TODAY</div>
<div class="tomorrow">TOMORROW</div>
Script:
function hideToday() {
var todayElements = document.getElementsByClassName('today'), i;
for (i = 0; i < todayElements.length; i += 1) {
todayElements[i].style.display = 'none';
};
};
var tomorrowElements = document.getElementsByClassName('tomorrow'), i;
for (i = 0; i < tomorrowElements.length; i += 1) {
tomorrowElements[i].style.display = 'none';
}
Upvotes: 1
Views: 3106
Reputation: 120548
The reason it doesn't work in jsfiddle is that your hideToday
function is out of scope. I don't know which scope the script in jsfiddle exists, but it seems it isn't global.
If you put the same code in a webpage and view it, it works as expected:
<html>
<body>
<input class="" name="options" id="opt1" type="radio" onClick="hideToday()"/><label for="opt1">Hide today</label>
<input class="" name="options" id="opt1" type="radio" onClick="hideToday()"/><label for="opt1">Hide today</label>
<br>
<br>
<div class="today">TODAY</div>
<div class="today">TODAY</div>
<div class="today">TODAY</div>
<br>
<div class="tomorrow">TOMORROW</div>
<script>
function hideToday() {
var todayElements = document.getElementsByClassName('today'), i;
for (i = 0; i < todayElements.length; i += 1) {
todayElements[i].style.display = 'none';
};
};
var appBanners = document.getElementsByClassName('tomorrow'), i;
for (i = 0; i < appBanners.length; i += 1) {
appBanners[i].style.display = 'none';
}
</script>
</body>
</html>
You can fix your fiddle by exporting hideToday
onto window
:
window["hideToday"] = hideToday;
Upvotes: 1
Reputation: 6947
If you want to use the onClick that way, which is a bad idea, you need to put your javascript in you Head
, so you can make your fiddle work just by changing the second select box on top left to No wrap - in <head>
But it would be better to not use inline javascript and put event handling in external file too.
Upvotes: 0