I'm rather new to web programming and javascript. I'm used to working with as3 or java for non-web projects.
I have written a bit of javascript to show and hide divs on a website. I wish to show the div that corresponds to a clicked menu item and hide all the others.
The code however, isn't working. I have tried several things but I im clearly not familiar enough with javascript to make it work.
Basically I want to add a .visibleContent class to the div I wish to show, so that css3 transition will make it fade in, and when the class is removed, css3 transitions will make it fade out.
could anyone please explain to me what im doing wrong? am I even approaching this the right way? I know of Jquery, but I think its overkill to import that library just for this. I would like to use javascript itself.
The links and divs in my html:
<li><a href="javascript:;" onClick='navClick("page1");'>page 1 button</a></li>
<li><a href="javascript:;" onClick='navClick("page2");'>page 2 button</a></li>
<div id="pages">
<div id="page1">
<p> page 1 content </p>
</div>
<div id="page2">
<p> page 2 content </p>
</div>
</div>
and here is the javascript, note that I have copied the hasClass, addClass and removeClass functions from here: dynamically add/remove style in javascript
var page1 = document.getElementById('page1');
var page2 = document.getElementById('page2');
var pageArray = new Array;
pageArray.push(page1);
pageArray.push(page2);
function hasClass(element,class) {
return element.className.match(new RegExp('(\\s|^)'+class+'(\\s|$)'));
}
function addClass(element,class) {
if (!this.hasClass(element,class)) element.className += " "+class;
}
function removeClass(ele,cls) {
if (hasClass(element,class)) {
var reg = new RegExp('(\\s|^)'+class+'(\\s|$)');
element.className=element.className.replace(reg,' ');
}
}
function navClick(id) {
var e = document.getElementById(id);
for (i = 0; i < pageArray.length; i++) {
if (pageArray[i] == e) {
if (!hasClass(pageArray[i], 'visibleContent')) {
addClass(pageArray[i], 'visibleContent');
}
} else {
if (hasClass(pageArray[i], 'visibleContent')) {
removeClass(pageArray[i], 'visibleContent');
}
}
}
}
here is the relevant css:
#pages div {
opacity: 0;
position: fixed;
width:55%;
height: 65%;
top: 10%;
left: 100%;
background: #00FF00;
animation fadeOutAnimation 1s linear 1;
}
.visibleContent {
opacity: 1;
position: fixed;
width: 55%;
height: 65%;
top:10%;
left:40%;
background: #00FF00;
animation: fadeInAnimation 1s linear 1;
}
when I add the .visibleContent class to a div directly in the html markup, the content shows up as it should, when I don't add the class to a div, it is indeed invisible. When I use my navClick function to try and add the class dynamically, nothing happens... Whats wrong?