Reputation: 19
Been learning jQuery today and have managed to make myself this slide menu, I was just wondering if there is a way to make the code more simplified?
Doesn't seem to work in the jsfiddle? but when you click about me, projects etc a box appears underneath..
Can this be made shorter to reduce the css or jquery code (or both) like using the same class for each different box would be good...
$( document ).ready(function() {
$("#box1").click(function() {
$('.dropbox').slideToggle("slow");
});
$("#box2").click(function() {
$('.dropbox2').slideToggle("slow");
});
$("#box3").click(function() {
$('.dropbox3').slideToggle("slow");
});
});
Upvotes: 1
Views: 208
Reputation: 123739
You can turn the ids
to just a common class names and attach just one handler to it.
HTML:
<div class="box">
<p>About me</p>
</div>
<div class="dropbox">
<p>a wild potato appeared</p>
</div>
<div class="box">Projects</div>
<div class="dropbox">
<p>ja</p>
</div>
<div class="box">Websites</div>
<div class="dropbox">
<p>hey</p>
</div>
JS:
$(document).ready(function () {
$(".box").click(function () {
$(this).next('.dropbox').slideToggle("slow");
});
});
CSS:
* {
margin: 0 auto;
}
.box:first-child{
margin-top: 20px;
}
.box {
background-color: red;
max-width: 470px;
padding: 10px;
}
.box:hover {
background-color: yellow;
}
.dropbox {
max-width: 470px;
padding: 10px;
background-color: black;
display: none;
color: white;
}
And btw you need to select jquery in your fiddle, from the left panel "Frameworks & Extensions".
And if you want to slideup other when toggling the current dropbox you can just do:
$(document).ready(function () {
var $dropBoxes = $('.dropbox');
$(".box").click(function () {
$dropBoxes.not($(this).next('.dropbox').slideToggle("slow")).slideUp('slow');
});
});
Upvotes: 1