I don´t work much with javascript and I googled a lot the last few hours to figure out my problem. I guess I just don´t know the right words to search for.
This is what I want to achieve. A list of Links with a small arrow next to it. When you click on a link, a hidden div is shown and the arrow should move down to show that the text is “open”. When I click on another text, the arrow should move up again and the div should be hidden. The other div would open accordingly. But the code is still a bit buggy. When I click on a link it gets the class “expanded” – but this class is not being automatically removed when I click on another item.
Here is my code so far… It doesnt work at all on jsfiddle, don´t know why http://jsfiddle.net/DvH75/
var _hidediv = null
function showdiv(id) {
if(_hidediv)
_hidediv();
var div = document.getElementById(id);
div.style.display = 'block';
$(".toggle").on("click", function(){
$(this).toggleClass("expanded");
});
_hidediv = function () { div.style.display = 'none'; };
}
And this is an example of what I want to archieve. The only difference is that I want an open item to close once another is opened:
https://www.facebook.com/help/473865172623776/
I hope you understand my question and can help me
Thank you very much!!
Your toggleClass() call is adding the class to the one clicked, but I don’t see you removing the class of the previous clicked. What I would do is something like:
EDIT: Working Example
I spent some time in jsFiddle and got this working example (warning, jsFiddler doesn’t seem to work in IE8, so use FireFox or Chrome to view the example).
First, I dropped the ‘display: none;‘ from the UL.fade_text li div style in main.css as it’s not needed any longer.
Next, I added class markers for all the *div*s. I could have probably done something else, but this was a quick-n-dirty example.
Last, I re-wrote the JS to be more jQuery-ish. I made a function that will show or hide the divs based on if it finds an anchor tag with the class toggle that also has the class expanded. Then, I added a click event handler to all the anchor tags, again using jQuery, that calls the showHideDivs() function. I also added a call to showHideDivs() in the $(document).ready() so that the initial state is set properly.
Here is the new JS code. It could probably be tweeked to optimize things a bit, but it works like I would expect:
I think the benefits of this approach is that it will gracefully degrade for browsers that have issues with the JS or just have JS turned off. The end result is that those people would see all the div tags expanded.