I have this jQuery code I've done to toggle floating sections with image previews. The layer is always the same, only the images change. I've manage to simplify the code in css giving classes to the elements. Everything works fine. However I'm finding it very hard to optimize the jQuery code. I'm pretty new to jQuery and Javascript so I'm not quite sure how to do this. The code works fine but It's massive huge and I want to simplify it. I believe I have to use variables. But how? Any help would be appreciated :)
this is my jQuery code:
//first layer
$(document).ready(function() {
$('.toggleLayer').click(function(){
$('#FloatingLayer').fadeIn('fast');
});
});
$(document).ready(function() {
$('#FloatingLayer').click(function(){
$(this).fadeOut('fast');
});
});
//second layer
$(document).ready(function() {
$('.toggleLayer2').click(function(){
$('#FloatingLayer2').fadeIn('fast');
});
});
$(document).ready(function() {
$('#FloatingLayer2').click(function(){
$(this).fadeOut('fast');
});
});
// third layer
$(document).ready(function() {
$('.toggleLayer3').click(function(){
$('#FloatingLayer3').fadeIn('fast');
});
});
$(document).ready(function() {
$('#FloatingLayer3').click(function(){
$(this).fadeOut('fast');
});
});
And here is my html:
<div class="fourcol toggleLayer">
<img src="img1" class="center" width="100%">
</div>
<div class="fourcol toggleLayer2">
<img src="img2.jpg" class="center" width="100%">
</div>
<div class="fourcol toggleLayer3">
<img src="img3" class="center" width="100%" >
</div>
the floating sections:
<section class="Floating" id="FloatingLayer">
<img src="img1.jpg" class="floatimg"/>
</section>
<section class="Floating" id="FloatingLayer2">
<img src="img2.jpg" class="floatimg"/>
</section>
<section class="Floating" id="FloatingLayer3">
<img src="img3.jpg" class="floatimg"/>
</section>
Take advantage of the fact that you can add information to your markup that guides behaviors supplied by your JavaScript code. Assuming your toggle controls are buttons:
edit — or with your actual markup:
You now can write one simple handler for all of them:
Similarly, one handler can do the work to close all the layers:
If you use event delegation as in these examples, you don't have to put the code in a "ready" handler.