Question

I'm a little stuck...

Take a look at this:

http://jsfiddle.net/matiitas/Lgtv5/1/

Below you can find part of the JavaScript code:

var stopPosition = 860;
var slidingDiv = "";
var slidingDiv2 = "";

window.onload = function () {
    document.getElementById("option").onclick = slideIt;
    slidingDiv = document.getElementById("content");
    document.getElementById("back").onclick = slideIn;

    document.getElementById("option2").onclick = slideIt2;
    slidingDiv2 = document.getElementById("content2");
    document.getElementById("back2").onclick = slideIn2;
};

function slideIt() {
    if (parseInt(slidingDiv.style.left) < stopPosition) {
        slidingDiv.style.left = parseInt(slidingDiv.style.left) + 2 + "px";
        setTimeout(slideIt, 1);
        active = true;
    }
}

I'm creating a sliding menu using javascript but I'm having 3 major issues:

  1. How can I reuse code so I don't have to "repeat" the functions over and over?
  2. I would like the menu "home" to hide when menu "Services" is clicked and viceversa.
  3. I would like to have the like to have two behaviors... when it's clicked for the first time to slide the content and when it's clicked again to hide the content...
Was it helpful?

Solution

1 - Something like this?

function slideIt(divToSlide) {
    if (parseInt(divToSlide.style.left) < stopPosition) {
        divToSlide.style.left = parseInt(divToSlide.style.left) + 2 + "px";
        setTimeout(slideIt, 1);
        active = true;
    }
}

Not sure what active is doing.

2 - Push all the elements that are animated into an array. When you expand one, collapse the others.

function slideIt(divToSlide) {
    for(var d in slidingDivs) {
        if(d != divToSlide) collapseDiv(d);
    }

    ...
}

3 - There are a few ways you could tackle this. Keep track of the state and check the state in your click handler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top