Home › Forums › JavaScript › Javascript fadeIn problem
- This topic is empty.
-
AuthorPosts
-
February 4, 2011 at 5:15 pm #31502renancoelhoMember
Hi there and thanks for the help!
I am new to javascript. There is probably a much easier way to do this with jquery. However, I am trying to learn javascript first, then move to jquery. I am trying to make a little album that when you click on a small pic it fades in into another div. The problem is that at first it fades in nicely, but then every time I select a new pic it loads faster and faster. To a point that after a while you cannot even notice the fading, because it is so fast. It took me a while to make this thing work, every time I came across a problem I would dig until I found an answer, but on this one I have no clue. Here is the code(is little for it is only a test)://initialize variables
imgList = document.getElementsByClassName('img');
top = document.getElementById('top')
bottom = document.getElementById('bottom')
len = imgList.length;
//top.style.opacity = 0;
//increase opacity slowly
function addOpacity(){
setInterval( function(){
if(top.style.opacity < 1){
top.style.opacity = parseFloat(top.style.opacity) + .02;//had a hard time to make it work because top.style.opacity was a string
}
}, 40);
}
//swap image
function swapImg(){
bottom.src = top.src;
top.src = this.src; // the word THIS represents the img clicked in the addEvent
top.style.opacity = 0;//sets it back to 0 before addOpacity() is ran
addOpacity()
}
//loop through the items
function addEvent(){
for (i = 0; i < len; i++){
imgList.addEventListener('click', swapImg, false)
}
};
//call the add event
addEvent()February 6, 2011 at 10:53 pm #62564renancoelhoMemberI still had no luck with this.. Anybody? thanks!
February 7, 2011 at 3:49 am #62536SirlonMemberEvery time you call addOpacity(); you start a new interval while the old one is still running, try to clear it first:
//initialize variables
var imgList = document.getElementsByClassName('img');
var top = document.getElementById('top');
var bottom = document.getElementById('bottom');
var len = imgList.length;
//top.style.opacity = 0;
var loop;
//increase opacity slowly
function addOpacity(){
loop = setInterval( function(){
if(top.style.opacity < 1){
top.style.opacity = parseFloat(top.style.opacity) + .02;//had a hard time to make it work because top.style.opacity was a string
}
}, 40);
}
//swap image
function swapImg(){
bottom.src = top.src;
top.src = this.src; // the word THIS represents the img clicked in the addEvent
top.style.opacity = 0;//sets it back to 0 before addOpacity() is ran
clearInterval(loop); // Clear your loop before init a new one
addOpacity();
}
February 7, 2011 at 11:22 am #62503renancoelhoMemberSirlon, Thanks so much! It was exactly that! Works great now! You rock!!!!
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.